-
1
module BxBlockLogin
-
1
class AccountAdapter
-
1
include Wisper::Publisher
-
-
1
def login_account(account_params)
-
7
case account_params.type
-
when 'sms_account'
-
phone = Phonelib.parse(account_params.full_phone_number).sanitized
-
account = AccountBlock::SmsAccount.find_by(
-
full_phone_number: phone,
-
activated: true)
-
when 'email_account'
-
7
email = account_params.email.downcase
-
-
7
account = AccountBlock::Account
-
.where('LOWER(email) = ?', email)
-
.where(activated: true, user_type: account_params.user_type)
-
.first
-
when 'social_account'
-
account = AccountBlock::SocialAccount.find_by(
-
email: account_params.email.downcase,
-
unique_auth_id: account_params.unique_auth_id,
-
activated: true)
-
end
-
-
7
unless account.present?
-
1
broadcast(:account_not_found)
-
1
return
-
end
-
-
6
if account.authenticate(account_params.password)
-
5
token, refresh_token = generate_tokens(account.id)
-
5
document_status = get_document_status(account)
-
5
last_visited_at = account.last_visit_at
-
5
first_time_login = set_first_time_login(account)
-
5
broadcast(:successful_login, account, token, refresh_token, document_status, last_visited_at, first_time_login)
-
else
-
1
broadcast(:failed_login)
-
end
-
end
-
-
1
def generate_tokens(account_id)
-
[
-
5
BuilderJsonWebToken.encode(account_id, 1.day.from_now, token_type: 'login'),
-
BuilderJsonWebToken.encode(account_id, 1.year.from_now, token_type: 'refresh')
-
]
-
end
-
-
1
def get_document_status(account)
-
5
@seller_documents = account.seller_documents
-
5
if @seller_documents.blank?
-
2
"No documents uploaded"
-
3
elsif @seller_documents.all?(&:approved?)
-
1
"Your document has been verified"
-
2
elsif @seller_documents.any?(&:rejected?)
-
1
rejected_documents = @seller_documents.select(&:rejected?).map(&:document_name)
-
1
"Rejected: #{rejected_documents.join(', ')}"
-
else
-
1
"Your Document verification is in progress"
-
end
-
end
-
-
1
def set_first_time_login(account)
-
5
if account.last_visit_at.nil? && @seller_documents.present? && @seller_documents.all?(&:approved?)
-
1
account.update(last_visit_at: Time.now)
-
1
return true
-
else
-
4
return false
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockActivitylog::ActivityLog, as: 'ActivityLogs' do
-
-
1
actions :show, :index, :delete
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :user_email
-
1
column :user_type
-
1
column :action
-
1
column :accessed_at
-
1
actions
-
end
-
-
1
filter :user
-
1
filter :user_type
-
1
filter :action
-
1
filter :details
-
1
filter :accessed_at
-
-
1
show do
-
1
attributes_table do
-
1
row :user
-
1
row :user_email
-
1
row :user_type
-
1
row :action
-
1
row :details
-
1
row :accessed_at
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockContactUs::AdminReply, as: 'Admin Reply' do
-
1
menu parent: 'Contact Us'
-
1
permit_params :description, :contact_id, :image, :created_at, :updated_at
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column 'Mail ID' do |contact|
-
2
contact.contact.email if contact.contact
-
end
-
1
column :description do |object|
-
2
truncate(object.description, length: 30)
-
end
-
1
column :image do |contact|
-
2
if contact.image.attached?
-
2
image_tag url_for(contact.image), height: '50'
-
else
-
content_tag(:span, "No image yet ")
-
end
-
end
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row 'Mail ID' do |contact|
-
1
contact.contact.email if contact.contact
-
end
-
1
row :description
-
1
row :image do |contact|
-
1
if contact.image.attached?
-
1
image_tag url_for(contact.image)
-
else
-
content_tag(:span, " No image yet")
-
end
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
form do |f|
-
2
f.inputs do
-
2
f.input :description, as: :text, input_html: { rows: 10 }
-
2
f.input :contact_id, as: :hidden
-
2
f.input :image, as: :file, hint: f.object.image.attached? ? image_tag(url_for(f.object.image), height: '50') : content_tag(:span, 'No image')
-
end
-
2
f.actions
-
end
-
-
1
controller do
-
1
def create
-
1
super do |format|
-
1
send_notification(resource) if resource.valid? && resource.persisted?
-
end
-
end
-
-
1
private
-
-
1
def send_notification(admin_reply)
-
2
BxBlockContactUs::AdminReplyMailer.notification(admin_reply).deliver_now
-
end
-
end
-
end
-
1
module AdminUsers
-
1
class Load
-
1
@@loaded_from_gem = false
-
1
def self.is_loaded_from_gem
-
1
@@loaded_from_gem
-
end
-
-
1
def self.loaded
-
end
-
-
# Check if this file is loaded from gem directory or not
-
# The gem directory looks like
-
# /template-app/.gems/gems/bx_block_custom_user_subs-0.0.7/app/admin/subscription.rb
-
# if it has block's name in it then it's a gem
-
1
@@loaded_from_gem = Load.method('loaded').source_location.first.include?('bx_block_')
-
end
-
end
-
-
1
unless AdminUsers::Load.is_loaded_from_gem
-
1
ActiveAdmin.register AdminUser do
-
1
menu priority: 2
-
1
permit_params :email, :password, :password_confirmation
-
-
1
index do
-
3
selectable_column
-
3
id_column
-
3
column :email
-
3
column :current_sign_in_at
-
3
column :sign_in_count
-
3
column :created_at
-
3
actions
-
end
-
-
1
filter :email
-
1
filter :current_sign_in_at
-
1
filter :sign_in_count
-
1
filter :created_at
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :email
-
1
f.input :password
-
1
f.input :password_confirmation
-
end
-
1
f.actions
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCustomAds::Advertisement, as: 'Custom Ads' do
-
294
menu if: proc { false }
-
1
permit_params :name, :description, :duration, :status, :start_at, :expire_at, :banner_ad
-
-
1
index do
-
8
selectable_column
-
8
id_column
-
8
column :name
-
8
column :description do |object|
-
8
truncate(strip_tags(object.description), length: 30)
-
end
-
8
column :duration
-
8
column :start_at
-
8
column :expire_at
-
8
column :status
-
8
actions
-
end
-
-
1
filter :name
-
1
filter :description
-
25
filter :status, as: :select, collection: proc { BxBlockCustomAds::Advertisement.statuses.map { |key, value| [key, BxBlockCustomAds::Advertisement.statuses[key]] } }
-
1
filter :start_at, as: :date_range
-
1
filter :expire_at, as: :date_range
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
form do |f|
-
2
f.inputs 'Advertisement Details' do
-
2
f.input :name
-
2
f.input :duration
-
2
f.input :start_at, as: :date_time_picker
-
2
f.input :expire_at, as: :date_time_picker
-
2
if f.object.banner_ad.attached?
-
f.input :banner_ad, as: :file, hint: image_tag(url_for(f.object.banner_ad), size: '100x100')
-
else
-
2
f.input :banner_ad, as: :file
-
end
-
2
f.input :status, as: :select, collection: BxBlockCustomAds::Advertisement.statuses.keys
-
2
f.input :description, as: :ckeditor
-
end
-
2
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :name
-
1
row :description do |object|
-
1
object.description&.html_safe
-
end
-
1
row :duration
-
1
row :start_at
-
1
row :expire_at
-
1
row :banner_ad do |ad|
-
1
image_tag url_for(ad.banner_ad), size: '100x100' if ad.banner_ad.attached?
-
end
-
1
row :status
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockDashboard::AuthorFavoriteBook, as: 'Author Favorite Book' do
-
1
permit_params :title,:status, favorite_book_catalogues_attributes: [:id, :catalogue_id, :_destroy]
-
1
menu parent: 'Home Page'
-
-
1
filter :title
-
1
filter :favorite_book_catalogues_catalogue_id, as: :select, collection: proc { BxBlockCatalogue::Catalogue.all.where(status: true).order(created_at: :desc).map { |obj| [obj.sku, obj.id] } }, label: "Products"
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs "Author Favorite Book Details" do
-
1
f.input :title
-
1
f.input :status
-
1
f.has_many :favorite_book_catalogues, heading: 'Catalogues', allow_destroy: true do |cs|
-
5
cs.input :catalogue_id, as: :select, collection: BxBlockCatalogue::Catalogue.all.where(status: true).order(created_at: :desc).map { |obj| [obj.sku, obj.id] }, label: 'Catalogue'
-
end
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :status
-
end
-
-
1
panel 'Catalogues' do
-
1
table_for resource.favorite_book_catalogues do
-
9
column('ID') { |selection| link_to selection.catalogue_id, admin_product_path(selection.catalogue_id) }
-
1
column :sku do |selection|
-
8
selection.catalogue.sku
-
end
-
1
column :besku do |selection|
-
8
selection.catalogue.besku
-
end
-
1
column :product_title do |selection|
-
8
selection.catalogue&.product_content&.product_title
-
end
-
1
column 'Actions' do |selection|
-
8
link_to 'View', admin_product_path(selection.catalogue_id)
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockDashboard::Banner, as: "Banners" do
-
1
menu label: "Dashboard Banners"
-
1
menu parent: 'Home Page'
-
-
1
permit_params :title, :description, :button_text, :button_link, :banner_type, :banner_group_id, :section, :banner_image, :category_id, :catalogue_id, :deal_id, :sub_category_id
-
-
1
filter :title
-
1
filter :description
-
1
filter :button_text
-
16
filter :banner_type, as: :select, collection: proc { BxBlockDashboard::Banner.banner_types.keys }
-
61
filter :banner_group_id, as: :select, collection: proc { BxBlockDashboard::BannerGroup.all.map { |g| [g.group_name, g.id] } }
-
61
filter :section, as: :select, collection: proc { BxBlockDashboard::Banner.sections.keys.map { |k| [k.to_s.humanize, k] } }
-
541
filter :category_id, as: :select, collection: proc { BxBlockCategories::Category.all.map { |c| [c.name, c.id] } }
-
136
filter :sub_category_id, as: :select, collection: proc { BxBlockCategories::SubCategory.all.map { |sc| [sc.name, sc.id] } }
-
61
filter :deal_id, as: :select, collection: proc { BxBlockCatalogue::Deal.all.active_deals.map { |d| [d.deal_name, d.id] } }
-
361
filter :catalogue_id, as: :select, collection: proc { BxBlockCatalogue::Catalogue.all.includes(:product_content).map { |c| [c.product_content&.product_title , c.id] } }
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
scope :all, default: true do |banners|
-
30
banners.where.not(banner_type: BxBlockDashboard::Banner.banner_types[:top_banner])
-
end
-
-
1
index do
-
15
selectable_column
-
15
id_column
-
15
column :title
-
15
column :description do |object|
-
45
truncate(strip_tags(object.description), length: 30)
-
end
-
15
column :button_text
-
15
column :banner_type
-
15
column :banner_group_name do |banner|
-
45
banner.banner_group.group_name if banner.banner_group.present?
-
end
-
15
column :section
-
15
column :banner_image do |banner|
-
45
image_tag(banner.banner_image, size: '100x100') if banner.banner_image.attached?
-
end
-
15
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :description do |object|
-
1
object.description&.html_safe
-
end
-
1
row :button_text
-
1
row :banner_type
-
1
row :banner_group_name do |banner|
-
1
banner.banner_group.group_name if banner.banner_group.present?
-
end
-
1
row :section
-
1
row :banner_image do |banner|
-
1
image_tag(banner.banner_image, size: '100x100') if banner.banner_image.attached?
-
end
-
1
row :category do |banner|
-
1
if banner.category.present?
-
1
link_to banner.category.name, admin_category_path(banner.category)
-
end
-
end
-
1
row :sub_category do |banner|
-
1
if banner.sub_category.present?
-
link_to banner.sub_category.name, admin_sub_category_path(banner.sub_category)
-
end
-
end
-
1
row :deal do |banner|
-
1
if banner.deal.present?
-
link_to banner.deal.deal_name, admin_deal_path(banner.deal)
-
end
-
end
-
1
row :catalogue do |banner|
-
1
if banner.catalogue.present?
-
link_to banner.catalogue.product_content&.product_title, admin_product_path(banner.catalogue)
-
end
-
end
-
end
-
end
-
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs 'Banner Details' do
-
1
f.input :section, as: :select, collection: BxBlockDashboard::Banner.sections.keys
-
1
f.input :banner_type, as: :select, collection: BxBlockDashboard::Banner.banner_types.keys, hint: "Slideshow only available for header and middle"
-
4
f.input :banner_group_id, as: :select, collection: BxBlockDashboard::BannerGroup.all.map { |g| [g.group_name, g.id] }, hint: "Banner group is only for slideshow type, please select accordingly"
-
1
if f.object.banner_image.attached?
-
1
f.input :banner_image, as: :file, hint: image_tag(url_for(f.object.banner_image), size: '100x100')
-
else
-
f.input :banner_image, as: :file
-
end
-
1
f.input :title
-
36
f.input :category_id, as: :select, collection: BxBlockCategories::Category.all.map { |c| [c.name, c.id] }
-
9
f.input :sub_category_id, as: :select, collection: BxBlockCategories::SubCategory.all.map { |sc| [sc.name, sc.id] }
-
4
f.input :deal_id, as: :select, collection: BxBlockCatalogue::Deal.all.active_deals.map { |d| [d.deal_name, d.id] }
-
5
f.input :catalogue_id, as: :select, collection: BxBlockCatalogue::Catalogue.all.includes(:product_content).where(status: true).map { |c| [c&.product_content&.product_title , c.id] }
-
1
f.input :button_text
-
1
f.input :description, as: :ckeditor
-
-
end
-
1
f.actions
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Barcode, as: 'Product Barcode' do
-
1
permit_params :bar_code, :status, :catalogue_id
-
-
294
menu if: proc { false }
-
-
1
form do |f|
-
1
f.inputs 'Barcode Details' do
-
-
1
selected_catalogue_id = params[:catalogue_id].presence || f.object.catalogue_id
-
23
f.input :catalogue_id, as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |c| [c.sku , c.id] }, selected: selected_catalogue_id
-
1
f.input :bar_code
-
-
1
f.input :status
-
end
-
-
1
f.actions do
-
1
f.action :submit
-
1
f.action :cancel, wrapper_html: { class: 'cancel' }
-
end
-
end
-
-
1
controller do
-
1
def update
-
-
1
update! do |format|
-
2
format.html { redirect_to admin_product_path(resource.catalogue) }
-
end
-
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Brand, as: 'Brands' do
-
1
menu parent: 'Brands'
-
1
permit_params :brand_name, :brand_name_arabic, :brand_year, :brand_website, :approve, :restricted, :gated, :branding_tradmark_certificate, :brand_image, :account_id
-
-
109
filter :account_id, as: :select, collection: proc { AccountBlock::Account.seller_accounts.map { |obj| [obj.first_name, obj.id] } }, label: "Seller"
-
1
filter :brand_name
-
1
filter :brand_year
-
1
filter :brand_website
-
1
filter :approve
-
1
filter :restricted
-
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
show do
-
1
attributes_table do
-
1
row "Seller", :account_id do |obj|
-
1
if obj.account_id.present?
-
1
link_to(obj&.account&.full_name, admin_seller_account_path(obj.account_id))
-
end
-
end
-
1
row :brand_name
-
1
row :brand_year
-
1
row :brand_website
-
1
row :brand_image do |brand|
-
1
image_tag(brand.brand_image, size: '100x100') if brand.brand_image.attached?
-
end
-
1
row :branding_tradmark_certificate do |brand|
-
1
if brand.branding_tradmark_certificate.attached?
-
link_to(brand.branding_tradmark_certificate.filename, url_for(brand.branding_tradmark_certificate), target: '_blank')
-
end
-
end
-
1
row :approve
-
1
row :restricted
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
index do
-
9
selectable_column
-
9
id_column
-
9
column :brand_name
-
9
column :brand_year
-
9
column :approve
-
9
column :restricted
-
9
column :created_at
-
9
column :updated_at
-
9
actions
-
end
-
-
1
form do |f|
-
1
f.inputs 'Brand Details' do
-
12
f.input :account_id, label: 'Seller', as: :select, collection: AccountBlock::Account.seller_accounts.map { |obj| ["#{obj&.full_name}", obj.id] }
-
1
f.input :brand_name
-
1
if f.object.brand_image.attached?
-
f.input :brand_image, as: :file, hint: image_tag(url_for(f.object.brand_image), size: '100x100')
-
else
-
1
f.input :brand_image, as: :file
-
end
-
1
f.input :brand_year
-
1
f.input :brand_website
-
1
if f.object.branding_tradmark_certificate.attached?
-
f.input :branding_tradmark_certificate, as: :file, hint: link_to(f.object.branding_tradmark_certificate.filename, url_for(f.object.branding_tradmark_certificate), target: '_blank')
-
else
-
1
f.input :branding_tradmark_certificate, as: :file
-
end
-
1
f.input :approve
-
1
f.input :restricted
-
end
-
1
f.actions
-
end
-
-
1
controller do
-
1
def destroy
-
2
@brand = BxBlockCatalogue::Brand.find(params[:id])
-
begin
-
2
if @brand.destroy
-
1
redirect_to admin_brands_path, notice: 'Brand deleted successfully.'
-
end
-
rescue => e
-
1
redirect_to admin_brands_path, alert: @brand.errors.full_messages.join(", ")
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "Buyer Account" do
-
-
1
scope "Buyer Accounts", :buyer_accounts, default: true do |accounts|
-
18
accounts.where(user_type: 'buyer')
-
end
-
-
1
permit_params :first_name, :last_name, :full_phone_number, :user_type, :email, :activated, :language
-
-
1
def buyer_filters
-
1
filter :first_name
-
1
filter :last_name
-
1
filter :full_phone_number
-
1
filter :phone_number
-
1
filter :email
-
1
filter :language, as: :select, collection: ['English']
-
1
filter :activated
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
end
-
-
1
buyer_filters
-
-
1
index do
-
9
selectable_column
-
9
id_column
-
9
column :email
-
9
column :first_name
-
9
column :last_name
-
9
column :full_phone_number
-
9
column :user_type
-
9
column :activated
-
9
column :created_at
-
9
column :updated_at
-
9
actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :email
-
2
row :first_name
-
2
row :last_name
-
2
row :full_phone_number
-
2
row :phone_number
-
2
row :user_type
-
2
row :language
-
2
row :activated
-
2
row :created_at
-
2
row :updated_at
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs 'Buyer Details' do
-
1
f.input :email
-
1
f.input :first_name
-
1
f.input :last_name
-
1
f.input :full_phone_number
-
1
f.input :user_type, as: :select, collection: ['seller', 'buyer']
-
1
f.input :language, as: :select, collection: ['English']
-
1
f.input :activated, as: :select, collection: [['Yes', true], ['No', false]]
-
end
-
1
f.actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::CatalogueContent, as: 'Catalogue Content' do
-
1
permit_params :custom_field_name, :value, :custom_field_id, :catalogue_id, :status
-
-
294
menu if: proc { false }
-
-
1
form do |f|
-
1
f.inputs 'Catalogue Content Details' do
-
1
f.hidden_field :custom_field_name, value: f.object.custom_field_name
-
1
f.hidden_field :custom_field_id, value: f.object.custom_field_id
-
1
f.hidden_field :catalogue_id, value: f.object.catalogue_id
-
1
f.input :value
-
end
-
-
1
f.actions
-
end
-
-
1
controller do
-
1
def update
-
-
1
update! do |format|
-
1
if resource.errors.any?
-
flash[:error] = resource.errors.full_messages.join(', ')
-
end
-
2
format.html { redirect_to admin_product_path(resource.catalogue) }
-
end
-
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::CatalogueOffer, as: 'Product Offers' do
-
1
permit_params :price_info, :sale_price, :bar_code_info, :sale_schedule_from, :sale_schedule_to, :warranty, :comments, :status, :catalogue_id, :barcode_id
-
-
294
menu if: proc { false }
-
-
1
form do |f|
-
1
f.semantic_errors
-
-
1
f.inputs 'Product Offer Details' do
-
1
f.input :price_info
-
1
f.input :sale_price
-
1
f.input :bar_code_info
-
1
f.input :sale_schedule_from, as: :date_time_picker
-
1
f.input :sale_schedule_to, as: :date_time_picker
-
1
f.input :warranty, as: :select, collection: ["1 Month", "2 Month", "3 Month", "6 Month", "1 Year", "2 Year"]
-
1
f.input :comments
-
-
1
selected_catalogue_id = params[:catalogue_id].presence || f.object.catalogue_id
-
1
f.input :catalogue, as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |c|
-
22
if c.is_variant
-
["#{c.sku} >> #{c.product_variant_group&.product_sku}", c.id]
-
else
-
22
[c.sku, c.id]
-
end
-
}, selected: selected_catalogue_id
-
-
1
f.input :barcode_id, as: :select, collection: BxBlockCatalogue::Barcode.all.map { |b| [b.bar_code, b.id] }, hint: "Create Barcode if not available"
-
1
f.input :status
-
end
-
-
1
f.actions do
-
1
f.action :submit
-
1
f.action :cancel, wrapper_html: { class: 'cancel' }
-
1
f.button 'Create Barcode', class: "button", type: :button, onclick: "window.open('/admin/product_barcodes/new', '_blank');"
-
end
-
end
-
-
1
controller do
-
1
def update
-
-
1
update! do |success, failure|
-
1
success.html do
-
1
redirect_to admin_product_path(resource.catalogue)
-
end
-
-
1
failure.html do
-
render edit_admin_product_offer_path(resource)
-
end
-
end
-
-
end
-
end
-
end
-
1
STATUS_OPTIONS = [['Approved', true], ['Not Approved', false]]
-
-
1
ActiveAdmin.register BxBlockCatalogue::Catalogue, as: 'Products' do
-
-
1
permit_params :sku, :besku, :bibc, :product_title, :product_image, :status, :category_id, :brand_id, :sub_category_id, :mini_category_id, :micro_category_id, :seller_id, :fulfilled_type,:product_type, :content_status, :recommended_priority
-
-
1
actions :new, :create, :index, :show, :edit, :update
-
-
1
scope :all, default: true do |catalogues|
-
35
catalogues.where.not(content_status: 'archived').order(created_at: :desc)
-
end
-
-
1
scope :archived do
-
19
BxBlockCatalogue::Catalogue.where(content_status: "archived").order(updated_at: :desc)
-
end
-
-
19
filter :category, as: :select, collection: proc { BxBlockCategories::Category.all.pluck(:name, :id) }
-
19
filter :brand_id, as: :select, collection: proc { BxBlockCatalogue::Brand.pluck(:brand_name, :id) }
-
19
filter :sub_category, as: :select, collection: proc { BxBlockCategories::SubCategory.all.pluck(:name, :id) }
-
19
filter :mini_category, as: :select, collection: proc { BxBlockCategories::MiniCategory.all.pluck(:name, :id) }
-
19
filter :micro_category, as: :select, collection: proc { BxBlockCategories::MicroCategory.all.pluck(:name, :id) }
-
73
filter :deal_catalogues, as: :select, collection: proc { BxBlockCatalogue::DealCatalogue.all.map { |dc| [dc.deal.deal_name, dc.id] } }
-
20
filter :catalogue_offer, as: :select, collection: proc { BxBlockCatalogue::CatalogueOffer.all.map { |offer| [offer.price_info, offer.id] } }
-
21
filter :barcode, as: :select, collection: proc { BxBlockCatalogue::Barcode.all.map { |code| [code.bar_code, code.id] } }
-
1
filter :product_content_retail_price, as: :numeric, label: 'Retail Price'
-
1
filter :product_content_mrp, as: :numeric, label: 'MRP'
-
235
filter :seller, as: :select, collection: proc { AccountBlock::Account.all.where(user_type: 'seller').map { |seller| [seller.full_name, seller.id] } }
-
1
filter :fulfilled_type, as: :select, collection: [["ByEzzy","byezzy"],["Partner","partner"]]
-
1
filter :product_type, as: :select, collection: [["Standard","standard"],["Rapid","rapid"]]
-
1
filter :content_status, as: :select, collection: [["Under Review","under_review"],["Accepted","accepted"],["Rejected","rejected"],["Archived","archived"]]
-
1
filter :sku_or_product_variant_group_product_sku_cont, as: :string, label: 'SKU' do |catalogues, value|
-
catalogues.joins(:product_variant_group)
-
.where('catalogues.sku ILIKE ? OR product_variant_groups.product_sku ILIKE ?', "%#{value}%", "%#{value}%")
-
end
-
1
filter :besku_or_product_variant_group_product_besku_cont, as: :string, label: 'BESKU' do |catalogues, value|
-
catalogues.joins(:product_variant_group)
-
.where('catalogues.besku ILIKE ? OR product_variant_groups.product_besku ILIKE ?', "%#{value}%", "%#{value}%")
-
end
-
1
filter :product_title
-
1
filter :is_variant
-
1
filter :status
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
18
selectable_column
-
18
id_column
-
18
column :sku
-
18
column :besku do |besku|
-
153
besku.product_variant_group&.product_besku || besku.besku
-
end
-
18
column :product_title do |product|
-
153
truncate(product.product_title, length: 30)
-
end
-
18
column :product_image do |product|
-
153
image_tag(product.product_image, size: '50x50') if product.product_image.attached?
-
end
-
18
column :is_variant
-
18
column :created_at
-
18
column :updated_at
-
18
column :status
-
18
actions defaults: false do |catalogue|
-
153
item "View", admin_product_path(catalogue), class: "view_link member_link"
-
153
item "Edit", edit_admin_product_path(catalogue), class: "edit_link member_link"
-
153
if params[:scope] == 'archived'
-
2
item "Unarchive", unarchive_admin_product_path(catalogue), class: "delete_link member_link", method: :put, data: { confirm: "Are you sure you want to unarchive this?" }
-
else
-
151
item "Archive", archive_admin_product_path(catalogue), class: "delete_link member_link", method: :put, data: { confirm: "Are you sure you want to archive this?" }
-
end
-
end
-
end
-
-
1
member_action :archive, method: :put do
-
1
resource.update(content_status: 'archived')
-
1
redirect_back(fallback_location: admin_products_path, notice: "Product archived.")
-
end
-
-
1
member_action :unarchive, method: :put do
-
1
resource.update(content_status: 'under_review')
-
1
redirect_back(fallback_location: admin_products_path, notice: "Product unarchived.")
-
end
-
-
1
form do |f|
-
2
f.inputs 'Catalogue Details' do
-
-
2
f.input :category, label: 'Category', as: :select,
-
collection: BxBlockCategories::Category.all.pluck(:name,:id)
-
-
2
f.input :brand, label: 'Brand', as: :select, collection: BxBlockCatalogue::Brand.pluck(:brand_name, :id)
-
2
f.input :sku
-
2
f.input :besku, as: :hidden
-
# , input_html: { readonly: true, value: f.object.parent_catalogue&.besku }
-
2
f.input :product_title
-
2
if f.object.product_image.attached?
-
1
f.input :product_image, as: :file, hint: image_tag(url_for(f.object.product_image), size: '100x100')
-
else
-
1
f.input :product_image, as: :file
-
end
-
2
f.input :fulfilled_type, as: :select, collection: [["ByEzzy","byezzy"],["Partner","partner"]]
-
2
f.input :product_type, as: :select, collection: [["Standard","standard"],["Rapid","rapid"]]
-
2
f.input :content_status, as: :select, collection: [["Under Review","under_review"],["Accepted","accepted"],["Rejected","rejected"],["Archived","archived"]]
-
2
selected_seller_id = params[:seller_id].presence || f.object.seller_id
-
26
f.input :seller_id, as: :select, collection: AccountBlock::Account.where(user_type: 'seller').all.map { |c| [c.full_name , c.id] }, selected: selected_seller_id
-
2
f.input :recommended_priority, as: :select, collection: (0..9)
-
2
f.input :status
-
end
-
-
2
f.actions
-
end
-
-
1
show do
-
4
attributes_table do
-
4
row :id
-
4
if resource&.is_variant
-
1
row :parent_product
-
end
-
4
row :sku
-
4
row :besku
-
4
row :bibc
-
4
row :product_title do |product|
-
4
div style: "width: 50%;" do
-
4
product.product_title
-
end
-
end
-
4
row :product_image do |product|
-
4
image_tag(product.product_image, size: '100x100') if product.product_image.attached?
-
end
-
4
row :seller do |product|
-
4
link_to product.seller.full_name, admin_seller_account_path(product.seller) if product.seller.present?
-
end
-
4
row :stocks
-
4
row :purchased_count
-
4
row :is_variant
-
4
row :recommended_priority
-
4
row :product_type
-
4
row :fulfilled_type
-
4
row :content_status
-
4
row :final_price
-
4
row :stroked_price
-
4
row :offer_percentage
-
4
row :status
-
4
row :created_at
-
4
row :updated_at
-
end
-
-
4
panel 'Categories' do
-
4
table_for [resource] do
-
4
column 'Category' do |catalogue|
-
4
catalogue.category.name if catalogue.category
-
end
-
-
4
column 'Subcategory' do |catalogue|
-
4
catalogue.sub_category.name if catalogue.sub_category
-
end
-
-
4
column 'MiniCategory' do |catalogue|
-
4
catalogue.mini_category.name if catalogue.mini_category
-
end
-
-
4
column 'MicroCategory' do |catalogue|
-
4
catalogue.micro_category.name if catalogue.micro_category
-
end
-
end
-
end
-
-
4
panel 'Brand' do
-
4
table_for resource.brand do
-
4
column :brand_name
-
4
column :brand_year
-
4
column :brand_website
-
4
column :approve
-
end
-
end
-
-
4
panel 'Contents' do
-
-
4
table_for resource.product_content do
-
4
if resource.product_content.present?
-
2
column :id
-
2
column :gtin
-
2
column :unique_psku
-
2
column :brand_name
-
2
column :product_title do |product|
-
2
truncate(product.product_title, length: 30)
-
end
-
2
column :mrp
-
2
column :retail_price
-
2
column 'Long Description' do |product|
-
2
truncate(product.long_description, length: 30)
-
end
-
2
column :whats_in_the_package do |product|
-
2
truncate(product.whats_in_the_package, length: 30)
-
end
-
2
column :country_of_origin
-
2
column :warranty_days
-
2
column :warranty_months
-
2
column 'Actions' do |content|
-
2
link_to 'View', admin_product_content_path(content)
-
end
-
else
-
2
div link_to('Create Content', new_admin_product_content_path(catalogue_id: resource.id), class: 'button')
-
2
br
-
end
-
end
-
-
end
-
-
4
panel 'Custom Fields Contents' do
-
4
table_for resource.catalogue_contents.order(created_at: :asc) do
-
4
if resource.catalogue_contents.present?
-
1
column :custom_field_name
-
1
column :value
-
1
column 'Actions' do |content|
-
1
link_to 'Edit', edit_admin_catalogue_content_path(content)
-
end
-
end
-
end
-
end
-
-
4
panel 'Product Variants' do
-
4
table_for resource.product_variant_group || resource.product_variant_groups do
-
4
column :product_sku
-
4
column :product_besku
-
4
column :product_bibc
-
4
column 'Actions' do |variant|
-
link_to 'View', admin_product_variant_group_path(variant)
-
end
-
end
-
4
unless resource.is_variant
-
3
div link_to('Create Variants', new_admin_product_variant_group_path(catalogue_id: resource.id), class: 'button')
-
end
-
4
br
-
end
-
-
4
panel 'Seller Deal' do
-
4
table_for resource.deal_catalogues do
-
4
if resource.deal_catalogues.present?
-
2
column :deal do |deal_catalogue|
-
2
deal_catalogue.deal.deal_name
-
end
-
2
column :deal_price
-
2
column :status
-
2
column 'Actions' do |seller_deal|
-
2
link_to 'View', admin_seller_deal_path(seller_deal)
-
end
-
else
-
2
div link_to('Create Seller Deal', new_admin_seller_deal_path(catalogue_id: resource.id), class: 'button')
-
2
br
-
end
-
-
end
-
end
-
-
4
panel 'Offer' do
-
4
table_for resource.catalogue_offer do
-
4
if resource.catalogue_offer
-
1
column :price_info
-
1
column :sale_price
-
1
column :bar_code_info
-
1
column :sale_schedule_from
-
1
column :sale_schedule_to
-
1
column :warranty
-
1
column :comments
-
1
column :status
-
1
column 'Actions' do |offer|
-
1
link_to 'View', admin_product_offer_path(offer)
-
end
-
else
-
3
div link_to('Create Offer', new_admin_product_offer_path(catalogue_id: resource.id), class: 'button')
-
3
br
-
end
-
end
-
end
-
-
4
panel 'Barcode' do
-
4
table_for resource.barcode do
-
4
if resource.barcode
-
1
column :bar_code
-
1
column :status
-
1
column 'Actions' do |barcode|
-
1
link_to 'View', admin_product_barcode_path(barcode)
-
end
-
else
-
3
div link_to('Create Barcode', new_admin_product_barcode_path(catalogue_id: resource.id), class: 'button')
-
3
br
-
end
-
end
-
end
-
-
4
active_admin_comments
-
end
-
-
-
1
action_item :archive, only: :show do
-
4
if resource.content_status == 'archived'
-
1
link_to 'Unarchive', unarchive_admin_product_path(resource), method: :put, data: { confirm: 'Are you sure you want to unarchive this?' }
-
else
-
3
link_to 'Archive', archive_admin_product_path(resource), method: :put, data: { confirm: 'Are you sure you want to archive this?' }
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCategories::Category, as: 'Category' do
-
-
1
permit_params :name,:category_image, :header_image, custom_fields_attributes: [:id, :field_name, :data_type, :mandatory, :_destroy, custom_fields_options_attributes: [:id, :option_name, :_destroy]]
-
-
-
1
filter :name
-
8
filter :sub_categories, as: :select, collection: proc { BxBlockCategories::SubCategory.pluck(:name, :id) }, label: 'Subcategory'
-
-
8
filter :mini_categories, as: :select, collection: proc { BxBlockCategories::MiniCategory.pluck(:name, :id) }, label: 'Mini Category'
-
-
8
filter :micro_categories, as: :select, collection: proc { BxBlockCategories::MicroCategory.pluck(:name, :id) }, label: 'Micro Category'
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
-
-
1
index do
-
7
selectable_column
-
7
id_column
-
7
column :name
-
7
column :category_image do |category|
-
94
image_tag(category.category_image, size: '50x50') if category.category_image.attached?
-
end
-
7
column :header_image do |category|
-
94
image_tag(category.header_image, size: '50x50') if category.header_image.attached?
-
end
-
7
column :created_at
-
7
column :updated_at
-
7
actions
-
end
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs do
-
1
f.input :name
-
1
if f.object.category_image.attached?
-
f.input :category_image, as: :file, hint: image_tag(url_for(f.object.category_image), size: '100x100')
-
else
-
1
f.input :category_image, as: :file
-
end
-
-
1
if f.object.header_image.attached?
-
f.input :header_image, as: :file, hint: image_tag(url_for(f.object.header_image), size: '100x100')
-
else
-
1
f.input :header_image, as: :file
-
end
-
end
-
-
1
f.has_many :custom_fields, allow_destroy: true, heading: 'Custom Fields', new_record: 'Add Custom Field' do |cf|
-
1
cf.input :field_name
-
1
cf.input :mandatory, as: :boolean
-
1
cf.has_many :custom_fields_options, allow_destroy: true, heading: 'Custom Field Options', new_record: 'Add Option' do |cfo|
-
1
cfo.input :option_name
-
end
-
end
-
-
1
f.actions
-
end
-
-
1
show do
-
-
1
panel 'Category' do
-
1
div style: 'display: flex; justify-content: space-between; ' do
-
-
1
div style: ' width: 65%;' do
-
1
attributes_table do
-
1
row :name
-
1
row :category_image do |category|
-
1
image_tag(category.category_image, size: '100x100') if category.category_image.attached?
-
end
-
1
row :header_image do |category|
-
1
image_tag(category.header_image, size: '100x100') if category.header_image.attached?
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
div style: 'width: 30%; text-align: left;' do
-
1
div do
-
1
h3 "Custom Fields"
-
end
-
1
table_for category.custom_fields do
-
1
column :field_name
-
1
column :mandatory
-
1
column :options do |field|
-
1
field.custom_fields_options.map(&:option_name).join(', ')
-
end
-
end
-
end
-
-
end
-
end
-
-
1
panel "Subcategories" do
-
1
div style: 'display: flex;justify-content: space-between;' do
-
1
div style: 'width: 65%; ' do
-
1
table_for category.sub_categories do
-
1
column "Subcategory Name" do |sub_category|
-
1
link_to sub_category.name, admin_sub_category_path(sub_category)
-
end
-
1
column :created_at
-
1
column :updated_at
-
1
column :custom_fields do |sub_category|
-
1
table_for sub_category.custom_fields do
-
1
column :field_name
-
1
column :mandatory
-
1
column :options do |field|
-
1
field.custom_fields_options.map(&:option_name).join(', ')
-
end
-
end
-
end
-
end
-
end
-
-
1
div style: ' width: 30%; text-align: right;' do
-
1
active_admin_form_for BxBlockCategories::SubCategory.new, url: admin_sub_categories_path do |f|
-
1
f.inputs "Create Subcategory" do
-
1
f.input :parent_id, as: :hidden, input_html: { value: category.id }
-
1
f.input :name
-
1
f.actions do
-
1
f.action :submit, label: "Add Sub Category"
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
panel "Minicategories" do
-
1
div style: 'display: flex; justify-content: space-between;' do
-
1
div style: ' width: 65%; ' do
-
1
table_for category.sub_categories.flat_map(&:mini_categories) do
-
1
column "Mini Category Name" do |mini_category|
-
1
link_to mini_category.name, admin_mini_category_path(mini_category)
-
end
-
1
column :created_at
-
1
column :updated_at
-
1
column :custom_fields do |mini_category|
-
1
table_for mini_category.custom_fields do
-
1
column :field_name
-
1
column :mandatory
-
1
column :options do |field|
-
1
field.custom_fields_options.map(&:option_name).join(', ')
-
end
-
end
-
end
-
end
-
end
-
-
1
div style: 'width: 30%;text-align: right;' do
-
1
active_admin_form_for BxBlockCategories::MiniCategory.new, url: admin_mini_categories_path do |f|
-
1
f.inputs "Create Mini category" do
-
1
f.input :parent_id, as: :hidden, input_html: { value: category.id }
-
1
f.input :name
-
2
f.input :sub_category, as: :select, collection: category.sub_categories.map { |s| [truncate(s.name, length: 40), s.id] }
-
1
f.actions do
-
1
f.action :submit, label: "Add Mini Category"
-
end
-
end
-
end
-
end
-
end
-
-
1
panel "Microcategories" do
-
1
div style: ' display: flex; justify-content: space-between;' do
-
1
div style: 'width: 65%; ' do
-
1
table_for category.sub_categories.flat_map(&:mini_categories).flat_map(&:micro_categories) do
-
1
column "Micro Category Name" do |micro_category|
-
1
link_to micro_category.name, admin_micro_category_path(micro_category)
-
end
-
1
column :created_at
-
1
column :updated_at
-
1
column :custom_fields do |micro_category|
-
1
table_for micro_category.custom_fields do
-
1
column :field_name
-
1
column :mandatory
-
1
column :options do |field|
-
1
field.custom_fields_options.map(&:option_name).join(', ')
-
end
-
end
-
end
-
end
-
end
-
-
1
div style: 'width: 30%; text-align: right; ' do
-
1
active_admin_form_for BxBlockCategories::MicroCategory.new, url: admin_micro_categories_path do |f|
-
1
f.inputs "Create Micro category" do
-
1
f.input :parent_id, as: :hidden, input_html: { value: category.id }
-
1
f.input :name
-
2
f.input :mini_category, as: :select, collection: category.sub_categories.flat_map(&:mini_categories).map { |m| [truncate(m.name, length: 40), m.id] }
-
1
f.actions do
-
1
f.action :submit, label: "Add Micro Category"
-
end
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockContactUs::Contact, as: 'Contact Us' do
-
1
menu parent: 'Contact Us'
-
1
permit_params :title, :email, :description, :contact_type, :image, :created_at, :updated_at
-
1
filter :contact_type
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :title
-
1
column :email
-
1
column :contact_type
-
1
column :description do |object|
-
3
truncate(strip_tags(object.description), length: 30)
-
end
-
1
column :image do |contact|
-
3
if contact.image.attached?
-
2
image_tag url_for(contact.image), height: '50'
-
else
-
1
content_tag(:span, "No image yet ")
-
end
-
end
-
1
column :created_at
-
1
column :updated_at
-
1
actions do |contact|
-
3
link_to 'Reply', new_admin_admin_reply_path(admin_reply: { contact_id: contact.id }), style: 'background-color: #48b1ff; padding: 5px 5px; border-radius: 3px;color:white;'
-
end
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :id
-
2
row :title
-
2
row :email
-
2
row :description do |object|
-
2
object.description&.html_safe
-
end
-
2
row :contact_type
-
2
row :image do |obj|
-
2
if obj.image.attached?
-
1
image_tag obj.image, width:200, height:200
-
else
-
1
content_tag(:span, " No image yet")
-
end
-
end
-
2
row :created_at
-
2
row :updated_at
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :title
-
1
f.input :email
-
4
f.input :contact_type, as: :select, collection: BxBlockContactUs::Contact.contact_types.keys.map { |type| [type.humanize, type] }
-
1
f.input :image, as: :file, hint: f.object.image.present? ? image_tag(f.object.image, size: '100x100') : content_tag(:span, " No image yet ")
-
1
f.input :description, as: :ckeditor
-
end
-
1
f.actions
-
end
-
-
-
end
-
1
ActiveAdmin.register BxBlockCouponCg::CouponCode, as: 'Coupons' do
-
294
menu if: proc { false }
-
1
permit_params :title, :code, :discount, :valid_from, :valid_to
-
1
actions :index, :show, :new, :create, :update, :edit
-
-
1
action_item :delete_coupon, only: [:show] do
-
1
if resource.persisted? && resource.subscribe_coupons.empty?
-
1
link_to 'Delete Coupon', delete_coupon_admin_coupon_path(resource), method: :delete
-
end
-
end
-
-
1
member_action :delete_coupon, method: :delete do
-
1
resource.destroy
-
1
redirect_to admin_coupons_path, notice: 'Coupon deleted successfully.'
-
end
-
-
1
scope 'All Coupons', default: true do |coupons|
-
2
BxBlockCouponCg::CouponCode.where(account_id: nil)
-
end
-
-
1
scope 'My Coupons' do |coupons|
-
1
BxBlockCouponCg::CouponCode.joins(:subscribe_coupons)
-
end
-
-
-
1
form do |f|
-
2
f.semantic_errors
-
2
f.inputs do
-
2
f.input :title, label: "Coupon Name"
-
2
f.input :code, label: "Coupon Code"
-
2
f.input :discount, input_html: { min: 0, type: 'text', class: 'required numeric-input' }
-
2
f.input :valid_from, label: "Start Date", as: :datepicker, input_html: { min: Date.current.to_s }
-
2
f.input :valid_to, label: "End Date", as: :datepicker, input_html: { min: Date.current.to_s }
-
end
-
2
f.actions
-
end
-
-
1
index do
-
1
selectable_column
-
1
column "Coupons Name", :title
-
1
column "Coupons Code", :code
-
1
column :discount
-
1
column "Start Date", :valid_from
-
1
column "End Date", :valid_to
-
1
actions defaults: false do |row|
-
1
div class: 'table_actions' do
-
1
text_node link_to "View", admin_coupon_path(row),method: :get, class: "view_link member_link"
-
1
text_node link_to "Edit", edit_admin_coupon_path(row), class: "edit_link member_link"
-
-
1
unless row.subscribe_coupons.present?
-
1
text_node link_to I18n.t('active_admin.delete'), delete_coupon_admin_coupon_path(row), method: :delete, data: { confirm: I18n.t('active_admin.delete_confirmation') }, class: "delete_link member_link"
-
end
-
end
-
end
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :code
-
1
row :discount
-
1
row :valid_from
-
1
row :valid_to
-
1
row :status
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCategories::CustomField, as: 'Custom Field' do
-
-
294
menu if: proc { false }
-
-
end
-
1
module Dashboard
-
1
class Load
-
1
@@loaded_from_gem = false
-
1
def self.is_loaded_from_gem
-
1
@@loaded_from_gem
-
end
-
-
1
def self.loaded
-
end
-
-
# Check if this file is loaded from gem directory or not
-
# The gem directory looks like
-
# /template-app/.gems/gems/bx_block_custom_user_subs-0.0.7/app/admin/subscription.rb
-
# if it has block's name in it then it's a gem
-
1
@@loaded_from_gem = Load.method('loaded').source_location.first.include?('bx_block_')
-
end
-
end
-
-
1
unless Dashboard::Load.is_loaded_from_gem
-
1
ActiveAdmin.register_page "Dashboard" do
-
1
menu priority: 1, label: proc { I18n.t("active_admin.dashboard") }
-
-
3
content title: proc { I18n.t("active_admin.dashboard") } do
-
1
div class: "blank_slate_container", id: "dashboard_default_message" do
-
1
span class: "blank_slate" do
-
1
span I18n.t("active_admin.dashboard_welcome.welcome")
-
1
small I18n.t("active_admin.dashboard_welcome.call_to_action")
-
end
-
end
-
end
-
294
menu if: proc { false }
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::DealCatalogue, as: 'Seller Deals' do
-
-
1
permit_params :status, :deal_price, :deal_id, :catalogue_id, :seller_id
-
-
8
filter :deal, collection: proc { BxBlockCatalogue::Deal.pluck(:deal_name, :id) }, label: 'Deal Name'
-
1
filter :catalogue_sku, as: :string, label: 'Catalogue SKU', filters: [:contains]
-
1
filter :status, as: :select, collection: { "Review" => 0, "Approved" => 1, "Rejected" => 2, "Expired" => 3 }
-
92
filter :seller, as: :select, collection: proc { AccountBlock::Account.all.where(user_type: 'seller').map { |seller| [seller.full_name, seller.id] } }
-
1
filter :deal_price
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
7
selectable_column
-
7
id_column
-
7
column 'Deal', sortable: :deal_id do |deal_catalogue|
-
13
deal_catalogue.deal.deal_name
-
end
-
7
column 'Catalogue', sortable: :catalogue_id do |deal_catalogue|
-
13
deal_catalogue.catalogue.is_variant ? deal_catalogue.catalogue&.product_variant_group&.product_sku : deal_catalogue.catalogue.sku
-
end
-
7
column 'Discount Type' do |deal_catalogue|
-
13
deal_catalogue.deal.discount_type
-
end
-
7
column :deal_price
-
7
column :current_offer_price
-
7
column :status
-
7
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :deal do |deal_catalogue|
-
-
1
link_to deal_catalogue.deal.deal_name, admin_deal_path(deal_catalogue.deal)
-
end
-
1
row 'Catalogue' do |deal_catalogue|
-
1
link_to (deal_catalogue.catalogue.is_variant ? deal_catalogue.catalogue&.product_variant_group&.product_sku : deal_catalogue.catalogue.sku), admin_product_path(deal_catalogue.catalogue)
-
end
-
1
row :seller
-
1
row :product_title
-
1
row :seller_price
-
1
row :current_offer_price
-
1
row :deal_price
-
1
row :status
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs 'Seller Deal Details' do
-
1
selected_seller_id = params[:seller_id].presence || f.object.seller_id
-
13
f.input :seller, as: :select, collection: AccountBlock::Account.where(user_type: 'seller').all.map { |c| [c.full_name , c.id] }, selected: selected_seller_id
-
1
f.input :deal, as: :select, collection: BxBlockCatalogue::Deal.active_deals.pluck(:deal_name, :id)
-
1
selected_catalogue_id = params[:catalogue_id].presence || f.object.catalogue_id
-
1
f.input :catalogue, as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |c|
-
23
if c.is_variant
-
["#{c.sku} >> #{c.product_variant_group&.product_sku}", c.id]
-
else
-
23
[c.sku, c.id]
-
end
-
}, selected: selected_catalogue_id
-
1
f.input :deal_price
-
1
f.input :status
-
end
-
1
f.actions
-
end
-
-
1
controller do
-
1
before_action :store_referer, only: [:edit]
-
-
1
def store_referer
-
1
session.delete(:previous_page) if session[:previous_page].present?
-
1
session[:previous_page] = request.referer || request.fullpath
-
end
-
-
1
def update
-
2
deal_catalogue_params = params.require(:deal_catalogue).permit(:status, :seller_id, :deal_id, :deal_price)
-
2
is_approved = deal_catalogue_params[:status] == 'approved'
-
2
redirect_path = session[:previous_page] || admin_deal_path(resource.deal)
-
-
2
if is_approved
-
1
resource.update_columns(deal_catalogue_params.to_h)
-
1
redirect_to redirect_path
-
else
-
1
update! do |success, failure|
-
2
success.html { redirect_to redirect_path }
-
1
failure.html { render edit_admin_seller_deal_path(resource) }
-
end
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Deal, as: 'Deals' do
-
-
1
permit_params :deal_name,:deal_code,:start_date,:end_date,:status,:discount_type, :discount_value
-
-
1
filter :deal_name
-
1
filter :deal_code
-
1
filter :discount_type
-
1
filter :start_date
-
1
filter :end_date
-
1
filter :status
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
8
selectable_column
-
8
id_column
-
8
column :deal_name
-
8
column :deal_code
-
8
column :discount_type
-
8
column :discount_value
-
8
column :start_date
-
8
column :end_date
-
8
column :status
-
8
actions
-
end
-
-
1
form do |f|
-
1
f.inputs 'Deal Details' do
-
1
f.input :deal_name
-
1
f.input :deal_code
-
1
f.input :discount_type, as: :select, collection: BxBlockCatalogue::Deal.discount_types.keys.map(&:to_s)
-
1
f.input :discount_value
-
1
f.input :start_date, as: :date_picker
-
1
f.input :end_date, as: :date_picker
-
1
f.input :status, as: :select, collection: [['Active', true], ['Inactive', false]]
-
end
-
1
f.actions
-
end
-
-
1
show do
-
-
1
attributes_table do
-
1
row :id
-
1
row :deal_name
-
1
row :deal_code
-
1
row :discount_type
-
1
row :discount_value
-
1
row :start_date
-
1
row :end_date
-
1
row :status
-
end
-
-
1
if resource.deal_catalogues.present?
-
1
panel 'Deal Catalogues' do
-
1
table_for resource.deal_catalogues.order(created_at: :desc) do
-
1
column :seller_sku do |deal_catalogue|
-
1
deal_catalogue.catalogue.is_variant ? "#{deal_catalogue.catalogue.sku} >> #{deal_catalogue.catalogue&.product_variant_group&.product_sku}" : deal_catalogue.catalogue.sku
-
end
-
1
column :product_title
-
1
column :seller_price
-
1
column :current_offer_price
-
1
column :deal_price
-
1
column 'Status' do |deal_catalogue|
-
1
deal_catalogue.status.capitalize
-
end
-
1
column 'Edit Status' do |deal_catalogue|
-
1
link_to 'Edit', edit_admin_seller_deal_path(deal_catalogue)
-
end
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockOrderManagement::DeliveryRequest, as: 'Delivery Requests' do
-
294
menu if: proc { false }
-
1
permit_params :warehouse_id, :warehouse_name, :seller_id, :order_id, :order_number, :address_1, :address_2, :status
-
-
7
filter :warehouse_id, as: :select, collection: proc { BxBlockCatalogue::Warehouse.pluck(:warehouse_name, :id) }
-
7
filter :seller_id, as: :select, collection: proc { AccountBlock::Account.where(user_type: 'seller').pluck(:full_name, :id) }
-
1
filter :warehouse_name
-
1
filter :order_number
-
1
filter :status, as: :select, collection: [['Pending','pending'], ['Accepted','accepted'], ['Rejected','rejected']]
-
1
filter :created_at
-
1
filter :updated_at
-
-
1
index do
-
6
selectable_column
-
6
column :id
-
6
column :warehouse
-
6
column :warehouse_name
-
6
column :order_number
-
6
column "Seller", :seller do |obj|
-
6
if obj.seller.present?
-
6
link_to(obj.seller&.full_name, admin_seller_account_path(obj.seller_id))
-
end
-
end
-
6
column :status
-
6
actions
-
end
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs 'Delivery Request Details' do
-
1
f.input :seller_id, as: :select, collection: AccountBlock::Account.where(user_type: 'seller').pluck(:full_name, :id)
-
1
f.input :warehouse_name, as: :select, collection: BxBlockCatalogue::Warehouse.pluck(:warehouse_name)
-
1
f.input :order_number, as: :string
-
1
f.input :address_1
-
1
f.input :address_2
-
1
f.input :status, as: :select, collection: [['Pending','pending'], ['Accepted','accepted'], ['Rejected','rejected']]
-
end
-
1
f.actions
-
end
-
-
-
1
controller do
-
1
before_action :fetch_order, only: [:create, :update]
-
-
1
private
-
-
1
def fetch_order
-
1
if params[:id] || params['delivery_request']['order_number']
-
1
order_number = params['delivery_request']['order_number']
-
1
warehouse_name = params['delivery_request']['warehouse_name']
-
1
order = BxBlockShoppingCart::Order.find_by(order_number: order_number)
-
1
warehouse = BxBlockCatalogue::Warehouse.find_by(warehouse_name: warehouse_name)
-
1
if order && warehouse
-
1
params['delivery_request']['order_id'] = order.id
-
1
params['delivery_request']['warehouse_id'] = warehouse.id
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::GatedBrand, as: 'Gated Brands Req' do
-
1
permit_params :brand_id, :approved
-
-
1
menu parent: 'Brands'
-
-
112
filter :brand, collection: -> { BxBlockCatalogue::Brand.all.map { |brand| [brand.brand_name, brand.id] } }, as: :select
-
1
filter :approved, as: :select, collection: [['Yes', true], ['No', false]]
-
1
filter :brand_catalogues_sku, as: :string, label: 'Catalogue SKU', filters: [:contains]
-
-
-
1
index do
-
3
selectable_column
-
3
id_column
-
3
column :brand
-
3
column :approved
-
3
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :brand
-
1
row :reseller_permit_document do |brand|
-
1
if brand.reseller_permit_document.attached?
-
1
link_to(brand.reseller_permit_document.filename, url_for(brand.reseller_permit_document), target: '_blank')
-
end
-
end
-
1
row :approved
-
1
panel 'Catalogues' do
-
1
table_for resource.brand.catalogues do
-
1
column :id
-
1
column :sku
-
1
column :besku
-
1
column 'Details' do |catalogue|
-
link_to 'View Details', admin_product_path(catalogue)
-
end
-
end
-
end
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs 'Gated Brand Details' do
-
2
f.input :brand, collection: BxBlockCatalogue::Brand.all.where(gated: true).map { |brand| [brand.brand_name, brand.id] }, prompt: 'Select Brand'
-
1
f.input :approved
-
end
-
1
f.actions
-
end
-
-
1
controller do
-
1
def scoped_collection
-
5
end_of_association_chain.includes(brand: [:catalogues])
-
end
-
end
-
-
294
menu if: proc { false }
-
-
end
-
1
ActiveAdmin.register BxBlockDashboard::HeaderCategory, as: 'Header Categories' do
-
1
menu parent: 'Home Page'
-
1
permit_params :sequence_no, :category_id
-
-
-
end
-
1
ActiveAdmin.register BxBlockCategories::MicroCategory, as: 'MicroCategory' do
-
1
permit_params :name, :mini_category_id, custom_fields_attributes: [:id, :field_name, :data_type, :mandatory, :_destroy, custom_fields_options_attributes: [:id, :option_name, :_destroy]]
-
-
-
1
form do |f|
-
3
f.inputs do
-
36
f.input :mini_category, as: :select, collection: BxBlockCategories::MiniCategory.all.map { |m| [m.name,m.id] }
-
3
f.input :name
-
end
-
-
3
f.has_many :custom_fields, allow_destroy: true, heading: 'Custom Fields', new_record: 'Add Custom Field' do |cf|
-
3
cf.input :field_name
-
3
cf.input :mandatory, as: :boolean
-
3
cf.has_many :custom_fields_options, allow_destroy: true, heading: 'Custom Field Options', new_record: 'Add Option' do |cfo|
-
3
cfo.input :option_name
-
3
br
-
end
-
end
-
-
3
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :name
-
1
row :mini_category do |micro_category|
-
1
micro_category&.mini_category&.name
-
end
-
1
row :sub_category do |micro_category|
-
1
micro_category&.sub_category&.name
-
end
-
1
row 'Category' do |mini_category|
-
1
micro_category&.category&.name
-
end
-
1
row "Custom Fields" do
-
1
ul do
-
1
table do
-
1
thead do
-
1
tr do
-
1
th "Field Name"
-
1
th "Mandatory"
-
1
th "Options"
-
end
-
end
-
1
tbody do
-
1
micro_category.custom_fields.each do |field|
-
1
tr do
-
1
td truncate(field.field_name, length: 30)
-
1
td field.mandatory ? "Yes" : "No"
-
1
td do
-
1
ul do
-
1
field.custom_fields_options.each do |option|
-
1
li truncate(option.option_name, length: 30)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
controller do
-
1
def create
-
2
create! do |success, failure|
-
2
success.html do
-
1
redirect_to admin_category_path(resource.category)
-
end
-
2
failure.html do
-
1
render new_admin_micro_category_path(resource)
-
end
-
end
-
end
-
-
1
def update
-
2
update! do |success, failure|
-
2
success.html do
-
1
redirect_to admin_category_path(resource.category)
-
end
-
2
failure.html do
-
1
render edit_admin_micro_category_path(resource)
-
end
-
end
-
end
-
-
1
def destroy
-
1
destroy! do |format|
-
2
format.html { redirect_to admin_category_path(resource.mini_category.sub_category.category) }
-
end
-
end
-
-
end
-
-
294
menu if: proc { false }
-
# menu parent: 'Categories'
-
-
end
-
1
ActiveAdmin.register BxBlockCategories::MiniCategory, as: 'MiniCategory' do
-
1
M_FIELD = "Field Name"
-
1
M_MANDATORY = "Mandatory"
-
1
M_OPTIONS = "Options"
-
1
permit_params :name,:sub_category_id,custom_fields_attributes: [:id, :field_name, :data_type, :mandatory, :_destroy, custom_fields_options_attributes: [:id, :option_name, :_destroy]]
-
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :name
-
1
row :sub_category do |mini_category|
-
1
mini_category.sub_category&.name
-
end
-
1
row 'Category' do |mini_category|
-
1
mini_category&.category&.name
-
end
-
1
row "Custom Fields" do
-
1
ul do
-
1
table do
-
1
thead do
-
1
tr do
-
1
th M_FIELD
-
1
th M_MANDATORY
-
1
th M_OPTIONS
-
end
-
end
-
1
tbody do
-
1
mini_category.custom_fields.each do |custom_field|
-
1
tr do
-
1
td custom_field.field_name
-
1
td custom_field.mandatory ? "Yes" : "No"
-
1
td do
-
1
ul do
-
1
custom_field.custom_fields_options.each do |option|
-
1
li option.option_name
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
-
1
form do |f|
-
3
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
3
f.inputs do
-
3
f.input :name
-
27
f.input :sub_category, as: :select, collection: BxBlockCategories::SubCategory.all.map { |c| [c.name,c.id] }
-
end
-
-
3
f.has_many :custom_fields, allow_destroy: true, heading: 'Custom Fields', new_record: 'Add Custom Field' do |cf|
-
3
cf.input :field_name
-
3
cf.input :mandatory, as: :boolean
-
3
cf.has_many :custom_fields_options, allow_destroy: true, heading: 'Custom Field Options', new_record: 'Add Option' do |cfo|
-
3
cfo.input :option_name
-
end
-
end
-
3
f.actions
-
end
-
-
1
controller do
-
1
def create
-
2
create! do |success, failure|
-
2
success.html do
-
1
redirect_to admin_category_path(resource.category)
-
end
-
2
failure.html do
-
1
render new_admin_mini_category_path(resource)
-
end
-
end
-
end
-
-
1
def update
-
2
update! do |success, failure|
-
2
success.html do
-
1
redirect_to admin_category_path(resource.category)
-
end
-
2
failure.html do
-
1
render edit_admin_mini_category_path(resource)
-
end
-
end
-
end
-
-
1
def destroy
-
1
destroy! do |format|
-
2
format.html { redirect_to admin_category_path(resource.sub_category.category) }
-
end
-
end
-
end
-
294
menu if: proc { false }
-
# menu parent: 'Categories'
-
-
end
-
1
ActiveAdmin.register BxBlockDashboard::MostPopularCategory, as: 'Most Popular Category' do
-
1
menu parent: 'Home Page'
-
1
permit_params :sequence_no, :category_id
-
-
-
end
-
1
ActiveAdmin.register BxBlockShoppingCart::OrderItem, as: 'OrderItem' do
-
294
menu if: proc { false }
-
-
1
actions :index, :show
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :order_id
-
1
row :quantity
-
1
row :price
-
1
row :taxable
-
1
row :taxable_value
-
1
row :order_status
-
1
row 'Catalogue' do |order_item|
-
1
panel "Catalogue Details" do
-
1
attributes_table_for order_item.catalogue do
-
2
row('ID') { |catalogue| link_to catalogue.id, admin_product_path(catalogue) }
-
1
row :sku
-
1
row :besku
-
1
row :product_title do |catalogue|
-
1
catalogue.product_content&.product_title
-
end
-
end
-
end
-
end
-
# row 'Favourite' do |order_item|
-
# favourite = BxBlockShoppingCart::OrderItem.get_favourites(order_item)
-
# status_tag(favourite, label: favourite ? 'Yes' : 'No')
-
# end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockOrderManagement::OrderStatus, as: 'Order Status' do
-
1
permit_params :name, :created_at, :updated_at
-
-
-
1
filter :name
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :name
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :name
-
1
row :status
-
end
-
end
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :name
-
end
-
1
f.actions
-
end
-
end
-
-
1
ActiveAdmin.register BxBlockShoppingCart::Order, as: 'Order' do
-
1
menu label: 'Orders'
-
-
1
actions :index, :show, :edit, :update
-
-
1
permit_params :order_status_id, :accepted
-
-
1
filter :order_number
-
1
filter :total_items
-
1
filter :order_status
-
6
filter :order_items_order_status_id_in, as: :select, label: 'Order Item Status', collection: -> {BxBlockOrderManagement::OrderStatus.pluck(:status, :id)}
-
1
filter :order_placed_at
-
1
filter :delivered_at
-
1
filter :accepted
-
-
381
filter :customer, collection: -> { AccountBlock::Account.all.map { |account| [account.full_name, account.id] } }
-
# filter :coupon_code, collection: -> { BxBlockCouponCg::CouponCode.all.map { |coupon| [coupon.code, coupon.id] } }
-
1
filter :total_fees
-
1
filter :total_tax
-
1
filter :final_price
-
1
filter :discount
-
-
126
filter :order_items_catalogue_id_in, as: :select, collection: -> { BxBlockCatalogue::Catalogue.all.map { |catalogue| [catalogue&.product_content&.product_title, catalogue&.id] } },
-
label: 'Catalogue'
-
-
1
index do
-
4
column :order_number
-
4
column :total_items
-
4
column :order_status
-
4
column :order_placed_at
-
4
column :delivered_at
-
4
column :accepted
-
4
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :order_number
-
1
row :total_fees
-
1
row :total_items
-
1
row :discount
-
1
row :total_tax
-
1
row :final_price
-
1
row :transaction_id
-
1
row :order_status
-
1
row :order_placed_at
-
1
row :delivered_at
-
1
row :accepted
-
1
row :customer do |order|
-
1
if order.customer.present?
-
1
link_to order.customer.full_name, admin_buyer_account_path(order.customer)
-
end
-
end
-
1
row :sellers do |order|
-
1
if order.sellers.present?
-
order.sellers.uniq.map do |seller|
-
link_to seller.full_name, admin_seller_account_path(seller)
-
end.join(', ').html_safe
-
end
-
end
-
1
row 'Shipping Address' do |order|
-
1
if order.shipping_address.present?
-
1
order.shipping_address.attributes.slice(
-
'first_name', 'last_name', 'address_1', 'address_2',
-
'phone_number', 'state', 'city', 'zip_code', 'address_type'
-
).values.join(', ')
-
end
-
end
-
# row :coupon_code do |order|
-
# if order.coupon_code.present?
-
# link_to order.coupon_code.code, admin_coupon_path(order.coupon_code)
-
# end
-
# end
-
end
-
-
1
panel 'Order Items' do
-
1
table_for order.order_items do
-
1
column('ID') { |order_item| link_to order_item.id, admin_order_item_path(order_item) }
-
1
column :quantity
-
1
column :price
-
1
column 'Catalogue' do |order_item|
-
catalogue = order_item.catalogue
-
if catalogue.is_a?(BxBlockCatalogue::Catalogue)
-
link_to catalogue&.product_content&.product_title, admin_product_path(catalogue)
-
end
-
end
-
1
column :order_status
-
1
column 'Actions' do |order_item|
-
link_to 'View', admin_order_item_path(order_item)
-
end
-
end
-
end
-
end
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs 'Order Details' do
-
1
f.input :order_status
-
1
f.input :accepted
-
end
-
1
f.actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::ParentCatalogue, as: 'Byezzy Products' do
-
1
permit_params :category_id, :brand_id, :sku, :besku, :prod_model_no, :details, :status, :product_title,
-
:sub_category_id, :mini_category_id, :micro_category_id, :product_image
-
-
# actions :index, :show, :edit, :update, :new, :create, :delete
-
294
menu if: proc { false }
-
-
1
index do
-
7
selectable_column
-
7
id_column
-
7
column :category
-
7
column :brand
-
7
column :sku
-
7
column :besku
-
7
column :product_title
-
7
column :prod_model_no
-
7
column :details
-
7
actions
-
end
-
-
1
filter :category
-
8
filter :brand, as: :select, collection: proc { BxBlockCatalogue::Brand.pluck(:brand_name, :id) }
-
1
filter :besku
-
1
filter :status
-
1
filter :product_title
-
-
1
form do |f|
-
2
f.inputs do
-
2
f.input :category
-
2
f.input :brand, as: :select, collection: BxBlockCatalogue::Brand.pluck(:brand_name, :id)
-
2
if f.object.new_record?
-
1
f.input :besku, as: :string, input_html: { readonly: true, value: f.object&.generate_unique_besku }
-
else
-
1
f.input :besku, as: :string, input_html: { readonly: true }
-
end
-
2
f.input :product_title
-
2
f.input :prod_model_no
-
2
if f.object.product_image.attached?
-
1
f.input :product_image, as: :file, hint: image_tag(url_for(f.object.product_image), size: '100x100')
-
else
-
1
f.input :product_image, as: :file
-
end
-
2
f.input :details
-
2
f.input :status
-
end
-
2
f.actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :id
-
2
row :category
-
2
row :brand
-
2
row :sku
-
2
row :besku
-
2
row :product_title
-
2
row :product_image do |product|
-
2
image_tag(product.product_image, size: '100x100') if product.product_image.attached?
-
end
-
2
row :prod_model_no
-
2
row :details
-
2
row :status
-
end
-
-
2
panel 'Catalogues' do
-
2
table_for resource.catalogues do
-
4
column('ID') { |catalogue| link_to catalogue.id, admin_product_path(catalogue) }
-
2
column :sku
-
2
column :besku
-
2
column :product_title
-
2
column :product_image do |catalogue|
-
2
image_tag(catalogue.product_image, size: '50x50') if catalogue.product_image.attached?
-
end
-
2
column :seller do |catalogue|
-
2
link_to catalogue.seller&.full_name, admin_seller_account_path(catalogue.seller) if catalogue.seller.present?
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockTermsandconditions::PrivacyAndLegalPolicy , as: 'Tax And Legal Policy' do
-
1
menu label: 'Seller Tax & legal policy'
-
1
permit_params :title, :content, :status
-
-
1
actions :index, :show, :edit, :update
-
-
1
form do |f|
-
f.semantic_errors
-
f.inputs do
-
f.input :title, as: :select, collection: ['Tax Policy', 'Legal Policy'], include_blank: false
-
f.input :content, as: :ckeditor
-
f.input :status
-
end
-
f.actions
-
end
-
-
1
index do
-
1
column :title
-
1
column :content do |page_content|
-
1
truncate(strip_tags(page_content.content), length: 50)
-
end
-
1
column :status
-
1
actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :title
-
2
row :content do |page_content|
-
2
page_content.content&.html_safe
-
end
-
2
row :status
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::ProductContent, as: 'Product Contents' do
-
1
permit_params do
-
permitted = [
-
4
:catalogue_id, :gtin, :unique_psku, :brand_name, :product_title, :mrp, :retail_price, :long_description,
-
:whats_in_the_package, :country_of_origin, :product_color,:warranty_days, :warranty_months,
-
:size_and_capacity_attributes, :shipping_detail_attributes,
-
image_urls_attributes: [:id, :url, :_destroy],
-
feature_bullets_attributes: [:id, :field_name, :value, :_destroy],
-
special_features_attributes: [:id, :field_name, :value, :_destroy]
-
]
-
-
4
if params[:product_content]
-
3
permitted << { size_and_capacity_attributes: [:id, :size, :size_unit, :capacity, :capacity_unit, :hs_code, :prod_model_name, :prod_model_number, :number_of_pieces, :_destroy] } if params[:product_content][:size_and_capacity_attributes]&.values&.any?(&:present?)
-
3
permitted << { shipping_detail_attributes: [:id, :shipping_length, :shipping_length_unit, :shipping_height, :shipping_height_unit, :shipping_width, :shipping_width_unit, :shipping_weight, :shipping_weight_unit, :_destroy] } if params[:product_content][:shipping_detail_attributes]&.values&.any?(&:present?)
-
end
-
-
4
permitted
-
end
-
-
294
menu if: proc { false }
-
-
1
index do
-
2
selectable_column
-
2
id_column
-
2
column :catalogue
-
2
column :gtin
-
2
column :unique_psku
-
2
column :brand_name
-
2
column :product_title do |product|
-
14
truncate(product.product_title, length: 30)
-
end
-
2
column :mrp
-
2
column :retail_price
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :catalogue
-
2
row :gtin
-
2
row :unique_psku
-
2
row :brand_name
-
2
row :product_title do |product|
-
2
div style: "width: 50%;" do
-
2
product.product_title
-
end
-
end
-
2
row :mrp
-
2
row :retail_price
-
2
row :long_description do |product|
-
2
div style: "width: 50%; " do
-
2
product.long_description
-
end
-
end
-
2
row :whats_in_the_package do |product|
-
2
div style: " width: 50%;" do
-
2
product.whats_in_the_package
-
end
-
end
-
2
row :country_of_origin
-
2
row :product_color
-
2
row :warranty_days
-
2
row :warranty_months
-
end
-
-
2
panel 'Size and Capacity' do
-
2
attributes_table_for resource.size_and_capacity do
-
2
row :size
-
2
row :size_unit
-
2
row :capacity
-
2
row :capacity_unit
-
2
row :hs_code
-
2
row :prod_model_name
-
2
row :prod_model_number
-
2
row :number_of_pieces
-
end
-
end
-
-
2
panel 'Shipping Detail' do
-
2
attributes_table_for resource.shipping_detail do
-
2
row :shipping_length
-
2
row :shipping_length_unit
-
2
row :shipping_height
-
2
row :shipping_height_unit
-
2
row :shipping_width
-
2
row :shipping_width_unit
-
2
row :shipping_weight
-
2
row :shipping_weight_unit
-
end
-
end
-
-
2
panel 'Image URLs' do
-
2
table_for resource.image_urls do
-
2
column :url
-
end
-
end
-
-
2
panel 'Feature Bullets' do
-
2
table_for resource.feature_bullets do
-
2
column :field_name
-
2
column :value
-
end
-
end
-
-
end
-
-
1
form do |f|
-
4
f.semantic_errors
-
4
f.inputs 'Product Content Details' do
-
4
selected_catalogue_id = params[:catalogue_id].presence || f.object.catalogue_id
-
96
f.input :catalogue_id, as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |c| [c.sku , c.id] }, selected: selected_catalogue_id
-
4
f.input :gtin
-
4
f.input :unique_psku
-
4
f.input :brand_name
-
4
f.input :product_title
-
4
f.input :mrp
-
4
f.input :retail_price
-
4
f.input :long_description
-
4
f.input :whats_in_the_package
-
4
f.input :country_of_origin
-
4
f.input :product_color, as: :string
-
4
f.input :warranty_days
-
4
f.input :warranty_months
-
end
-
-
4
f.inputs 'Size and Capacity' do
-
4
f.semantic_fields_for :size_and_capacity_attributes, (f.object.size_and_capacity || f.object.build_size_and_capacity) do |size_and_capacity|
-
4
size_and_capacity.input :size
-
4
size_and_capacity.input :size_unit
-
4
size_and_capacity.input :capacity
-
4
size_and_capacity.input :capacity_unit
-
4
size_and_capacity.input :hs_code
-
4
size_and_capacity.input :prod_model_name
-
4
size_and_capacity.input :prod_model_number
-
4
size_and_capacity.input :number_of_pieces
-
end
-
end
-
-
4
f.inputs 'Shipping Detail' do
-
4
f.semantic_fields_for :shipping_detail_attributes, (f.object.shipping_detail || f.object.build_shipping_detail) do |shipping_detail|
-
4
shipping_detail.input :shipping_length
-
4
shipping_detail.input :shipping_length_unit
-
4
shipping_detail.input :shipping_height
-
4
shipping_detail.input :shipping_height_unit
-
4
shipping_detail.input :shipping_width
-
4
shipping_detail.input :shipping_width_unit
-
4
shipping_detail.input :shipping_weight
-
4
shipping_detail.input :shipping_weight_unit
-
end
-
end
-
-
4
f.inputs 'Image URLs*' do
-
4
f.has_many :image_urls, allow_destroy: true do |image_url|
-
7
image_url.input :url
-
end
-
end
-
-
4
f.inputs 'Feature Bullets*' do
-
4
f.has_many :feature_bullets, allow_destroy: true do |feature_bullet|
-
7
feature_bullet.input :field_name, hint: "(e.g., Feature Bullet 1, Feature Bullet 2, ...)"
-
7
feature_bullet.input :value
-
end
-
end
-
-
4
f.actions
-
end
-
-
1
controller do
-
-
1
def create
-
2
super do |success, failure|
-
2
failure.html do
-
2
flash[:main_model_errors] = resource.errors.full_messages.join(', ')
-
2
if resource.image_urls.blank?
-
2
flash[:image_urls_errors] = "Image URLs: At least one Image Url must be present"
-
end
-
2
if resource.feature_bullets.blank?
-
2
flash[:feature_bullets_errors] = "Feature Bullets: At least one Feature Bullet must be present"
-
end
-
-
2
render :new
-
end
-
end
-
end
-
-
1
def update
-
1
super do |success, failure|
-
1
failure.html do
-
1
flash[:main_model_errors] = resource.errors.full_messages.join(', ')
-
1
if resource.image_urls.blank?
-
flash[:image_urls_errors] = "Image URLs: At least one Image Url must be present"
-
end
-
1
if resource.feature_bullets.blank?
-
flash[:feature_bullets_errors] = "Feature Bullets: At least one Feature Bullet must be present"
-
end
-
-
1
render :edit
-
end
-
end
-
end
-
-
1
def destroy
-
def destroy
-
destroy! do |format|
-
format.html { redirect_to admin_product_path(resource.catalogue), notice: "Product Content was successfully destroyed." }
-
end
-
end
-
end
-
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::ProductVariantGroup, as: 'Product Variant Groups' do
-
1
permit_params :product_sku, :product_description, :price, :product_title, :catalogue_id, product_images: [], group_attributes_attributes: [:id, :attribute_name, :option, :_destroy]
-
-
294
menu if: proc { false }
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :product_sku
-
1
column :product_besku
-
1
column :product_bibc
-
1
actions
-
end
-
-
1
form do |f|
-
2
f.semantic_errors
-
-
2
f.inputs 'Product Variant Group Details' do
-
2
selected_catalogue_id = params[:catalogue_id].presence || f.object.catalogue_id
-
-
47
f.input :catalogue_id, as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |c| [c.sku, c.id] }, selected: selected_catalogue_id
-
2
f.input :product_sku
-
end
-
-
2
f.inputs 'Group Attributes' do
-
2
f.has_many :group_attributes, allow_destroy: true, new_record: 'Add Attribute' do |attribute|
-
2
attribute.input :attribute_name
-
2
attribute.input :option
-
end
-
end
-
-
2
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :product_sku
-
1
row :product_besku
-
1
row :product_bibc
-
1
row :catalogue
-
end
-
-
1
panel 'Group Attributes' do
-
1
table_for resource.group_attributes.order(created_at: :desc) do
-
1
column :attribute_name
-
1
column :option
-
end
-
end
-
end
-
-
1
controller do
-
1
def update
-
-
2
update! do |format|
-
2
if resource.errors.any?
-
flash[:error] = resource.errors.full_messages.join(', ')
-
end
-
4
format.html { redirect_to admin_product_path(resource.catalogue) }
-
end
-
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::RestrictedBrand, as: 'Restricted Brand Requests' do
-
1
permit_params :brand_id, :approved, :reseller_permit_document, :seller_id
-
-
1
menu parent: 'Brands'
-
-
112
filter :brand, collection: -> { BxBlockCatalogue::Brand.all.map { |brand| [brand.brand_name, brand.id] } }, as: :select
-
40
filter :seller_id, as: :select, collection: proc { AccountBlock::Account.seller_accounts.map { |obj| [obj.full_name, obj.id] } }, label: "Sellers"
-
1
filter :approved, as: :select, collection: [['Yes', true], ['No', false]]
-
-
1
index do
-
3
selectable_column
-
3
id_column
-
3
column :brand
-
3
column :approved
-
3
column :reseller_permit_document do |brand|
-
6
link_to('Download Document', url_for(brand.reseller_permit_document), target: '_blank') if brand.reseller_permit_document.present?
-
end
-
3
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :brand
-
1
row "Sellers", :seller_id do |obj|
-
1
if obj.seller_id.present?
-
1
link_to(obj&.seller&.full_name, admin_seller_account_path(obj.seller_id))
-
end
-
end
-
1
row :approved
-
1
row :reseller_permit_document do |brand|
-
1
link_to('Download Document', url_for(brand.reseller_permit_document), target: '_blank') if brand.reseller_permit_document.present?
-
end
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs 'Restricted Brand Details' do
-
3
f.input :brand, collection: BxBlockCatalogue::Brand.all.where(restricted: true).map { |brand| [brand.brand_name, brand.id] }, prompt: 'Select Brand'
-
13
f.input :seller_id, label: 'Sellers', as: :select, collection: AccountBlock::Account.seller_accounts.map { |obj| ["#{obj&.full_name}", obj.id] }
-
1
f.input :reseller_permit_document, as: :file
-
1
f.input :approved
-
end
-
1
f.actions
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Review, as: 'Reviews' do
-
1
permit_params :rating, :title, :description, :catalogue_id, :is_approved, :order_item_id, :reviewer_id, :account_id, :review_type
-
1
scope :product_feedbacks do
-
5
BxBlockCatalogue::Review.where(review_type: "product").order(id: :desc)
-
end
-
-
1
scope :seller_feedbacks do
-
5
BxBlockCatalogue::Review.where(review_type: "seller").order(id: :desc)
-
end
-
-
1
scope :delivery_feedbacks do
-
5
BxBlockCatalogue::Review.where(review_type: "delivery").order(id: :desc)
-
end
-
-
1
filter :title
-
1
filter :description
-
1
filter :rating
-
1
filter :review_type, :as => :select, :collection => ['product', 'seller', 'delivery']
-
66
filter :account_id, as: :select, collection: proc { AccountBlock::Account.seller_accounts.map { |obj| [obj.first_name, obj.id] } }, label: "Sellers"
-
46
filter :reviewer_id, as: :select, collection: proc { AccountBlock::Account.buyer_accounts.map { |obj| [obj.first_name, obj.id] } }, label: "Reviewers"
-
131
filter :catalogue_id, as: :select, collection: proc { BxBlockCatalogue::Catalogue.all.map { |obj| [obj.product_title, obj.id] } }, label: "Products"
-
-
1
csv do
-
column :id
-
column :title
-
column :description
-
column :rating
-
column :catalogue_id do |obj|
-
obj&.catalogue&.product_title
-
end
-
column :account_id do |obj|
-
seller = AccountBlock::Account.seller_accounts.find_by(id: obj.account_id)
-
seller&.first_name
-
end
-
column :reviewer_id do |obj|
-
obj&.account&.first_name
-
end
-
column :review_type
-
column :created_at
-
column :updated_at
-
end
-
-
1
form do |f|
-
3
f.semantic_errors
-
3
f.inputs do
-
3
f.input :title, label: "Title"
-
3
f.input :description, label: "Description", as: :text, input_html: { rows: 5 }
-
3
f.input :rating, hint: "rating should be between 1 and 5", input_html: { min: 1, max: 5, type: 'float', class: 'required numeric-input', step: 1 }
-
3
f.input :review_images, as: :file, input_html: { multiple: true }
-
3
if f.object.review_images.present?
-
1
div style: 'display: flex; flex-wrap: wrap;' do
-
1
f.object.review_images.each do |image|
-
1
span style: 'margin: 5px;' do
-
1
image_tag(image, size: '100x100')
-
end
-
end
-
end
-
end
-
9
f.input :order_item_id, label: 'Order Item', as: :select, collection: BxBlockShoppingCart::OrderItem.all.map { |obj| [obj.catalogue&.product_title, obj.id] }
-
78
f.input :catalogue_id, label: 'Products', as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |obj| ["#{obj.product_title}", obj.id] }
-
27
f.input :reviewer_id, label: 'Reviewers', as: :select, collection: AccountBlock::Account.buyer_accounts.map { |obj| ["#{obj&.full_name}", obj.id] }
-
39
f.input :account_id, label: 'Sellers', as: :select, collection: AccountBlock::Account.seller_accounts.map { |obj| ["#{obj&.full_name}", obj.id] }
-
3
f.input :review_type, label: 'Review Type', as: :select, collection: ['product', 'seller', 'delivery']
-
3
f.input :is_approved
-
end
-
3
f.actions
-
end
-
-
1
index do
-
5
selectable_column
-
5
column "Products", :catalogue_id do |obj|
-
60
link_to(obj&.catalogue&.product_title, admin_product_path(obj&.catalogue_id))
-
end
-
5
column :rating
-
5
column :review_type
-
5
column "Title", :title
-
5
column "Reviewers", :reviewer_id do |obj|
-
60
link_to(obj&.account&.first_name, admin_buyer_account_path(obj&.reviewer_id))
-
end
-
5
column "Sellers", :account_id do |obj|
-
60
seller = AccountBlock::Account.seller_accounts.find_by(id: obj.account_id)
-
60
if seller.present?
-
55
link_to(seller&.first_name, admin_seller_account_path(seller.id))
-
else
-
5
"No seller added"
-
end
-
end
-
5
column :created_at
-
5
column :updated_at
-
5
toggle_bool_column "Approved", :is_approved
-
5
actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :title
-
2
row :description
-
2
row :rating
-
2
row :review_type
-
2
row "Products", :catalogue_id do |obj|
-
2
link_to(obj&.catalogue&.product_title, admin_product_path(obj&.catalogue_id))
-
end
-
2
row "Order Item", :order_item_id do |obj|
-
2
link_to(obj&.order_item&.id, admin_order_item_path(obj&.order_item)) if obj&.order_item.present?
-
end
-
2
row "Reviewers", :reviewer_id do |obj|
-
2
link_to(obj&.account&.first_name, admin_buyer_account_path(obj&.reviewer_id))
-
end
-
2
row "Sellers", :account_id do |obj|
-
2
seller = AccountBlock::Account.seller_accounts.find_by(id: obj.account_id)
-
2
if seller.present?
-
1
link_to(seller&.first_name, admin_seller_account_path(seller.id))
-
else
-
1
"No seller added"
-
end
-
end
-
2
row :review_images do |review|
-
2
div style: 'display: flex; flex-wrap: wrap;' do
-
2
review.review_images.each do |image|
-
1
span style: 'margin: 5px;' do
-
1
link_to(image_tag(image, size: '100x100'), url_for(image), target: '_blank')
-
end
-
end
-
end
-
end
-
2
row :is_approved
-
2
row :created_at
-
2
row :updated_at
-
end
-
end
-
end
-
1
ActiveAdmin.register_page "Sales Report" do
-
1
menu priority: 1, label: "Sales Report"
-
294
menu if: proc { false }
-
-
1
content title: "Sales Performance Report" do
-
1
panel "Generate Sales Report" do
-
1
render partial: '/admin/bx_block_salesreporting/sales_report_form'
-
end
-
-
1
div id: 'report-results' do
-
end
-
end
-
-
1
page_action :generate_report, method: :post do
-
3
period = params[:period]
-
3
report_type = params[:report_type]
-
3
category_id = params[:category_id]
-
-
3
case period
-
when 'daily'
-
1
start_date = Date.today.beginning_of_day
-
1
end_date = Date.today.end_of_day
-
else
-
2
start_date = params[:start_date].to_date
-
2
end_date = params[:end_date].to_date
-
end
-
-
3
report_service = BxBlockSalesreporting::SalesReportService.new(start_date, end_date, report_type, category_id)
-
3
report = report_service.call
-
-
3
respond_to do |format|
-
3
format.html do
-
render json: report
-
end
-
3
format.json do
-
1
send_data report.to_json, filename: "sales_report_#{Time.now.to_i}.json"
-
end
-
3
format.xml do
-
2
send_data report.to_xml, filename: "sales_report_#{Time.now.to_i}.xml"
-
end
-
end
-
end
-
-
# action_item :download_report, only: :index do
-
# link_to 'Download as JSON', admin_sales_report_generate_report_path(format: :json), method: :post
-
# end
-
-
# action_item :download_report, only: :index do
-
# link_to 'Download as XML', admin_sales_report_generate_report_path(format: :xml), method: :post
-
# end
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "Seller Account" do
-
-
1
scope "Seller Accounts", :seller_accounts, default: true do |accounts|
-
18
accounts.where(user_type: 'seller')
-
end
-
-
1
permit_params :first_name, :last_name, :full_phone_number, :phone_number, :user_type, :email, :gender, :date_of_birth, :age, :activated, :language
-
-
1
def seller_filters
-
1
filter :first_name
-
1
filter :last_name
-
1
filter :full_phone_number
-
1
filter :phone_number
-
1
filter :email
-
1
filter :company_or_store_name
-
1
filter :language, as: :select, collection: [['English', 'english']]
-
1
filter :activated
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
end
-
-
1
seller_filters
-
-
1
index do
-
9
selectable_column
-
9
id_column
-
9
column :email
-
9
column :first_name
-
9
column :last_name
-
9
column :full_phone_number
-
9
column :user_type
-
9
column :activated
-
9
column :created_at
-
9
column :updated_at
-
9
actions
-
end
-
-
1
form do |f|
-
1
f.inputs 'Seller Details' do
-
1
f.input :email
-
1
f.input :first_name
-
1
f.input :last_name
-
1
f.input :full_phone_number
-
1
f.input :company_or_store_name, label: "Company / Store Name"
-
1
f.input :user_type, as: :select, collection: ['seller', 'buyer']
-
1
f.input :language, as: :select, collection: ['English']
-
1
f.input :activated, as: :select, collection: [['Yes', true], ['No', false]]
-
end
-
1
f.actions
-
end
-
-
1
show do
-
3
columns do
-
3
column do
-
3
attributes_table do
-
3
row :email
-
3
row :first_name
-
3
row :last_name
-
3
row :full_phone_number
-
3
row :phone_number
-
3
row :company_or_store_name
-
3
row :user_type
-
3
row :language
-
3
row :activated
-
3
row :created_at
-
3
row :updated_at
-
end
-
end
-
-
3
column do
-
3
panel "Seller Documents" do
-
3
table_for seller_account.seller_documents.order(created_at: :asc) do
-
3
column :document_type
-
3
column :document_name
-
3
column :approved
-
3
column :rejected
-
3
column :actions do |seller_document|
-
1
link_to "View", admin_seller_document_path(seller_document)
-
end
-
end
-
end
-
end
-
-
end
-
end
-
-
1
controller do
-
1
def destroy
-
2
@seller_account = AccountBlock::Account.find(params[:id])
-
2
@flash_error_alert = "Cannot delete seller account. Please delete associated products and brands."
-
2
if @seller_account.destroy
-
1
flash[:notice] = "Seller account successfully deleted."
-
else
-
flash[:alert] = @flash_error_alert
-
end
-
1
redirect_to admin_seller_accounts_path
-
rescue ActiveRecord::InvalidForeignKey
-
1
flash[:alert] = @flash_error_alert
-
1
redirect_to admin_seller_accounts_path
-
end
-
end
-
end
-
1
ActiveAdmin.register AccountBlock::SellerDocument, as: 'SellerDocument' do
-
-
1
before_action :update_approved, only: [:update]
-
1
permit_params :approved, :rejected, :reason_for_rejection, :document_type
-
-
1
index do
-
2
selectable_column
-
2
id_column
-
2
column :account_id
-
2
column :document_type
-
2
column :approved
-
2
column :rejected
-
2
actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :account_id
-
2
row :document_type
-
2
row :document_name
-
2
if seller_document.document_type == "VAT Certificate or Reason for not having it"
-
row :vat_reason
-
end
-
2
if seller_document.document_type == "IBAN Certificate or Bank Details"
-
row :account_no
-
row :iban
-
row :bank_address
-
row :name
-
row :bank_name
-
row :swift_code
-
end
-
2
row :document_files do |seller_document|
-
2
ul do
-
2
seller_document.document_files.each do |file|
-
2
li link_to(file.filename, url_for(file), target: '_blank')
-
end
-
end
-
end
-
2
row :approved
-
2
row :rejected
-
2
row :reason_for_rejection
-
2
row :created_at
-
2
row :updated_at
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :approved, as: :boolean
-
1
f.input :rejected, as: :boolean
-
-
1
li do
-
1
f.input :reason_for_rejection, as: :text, rows: 4,style: 'float: left;clear: both;'
-
end
-
-
end
-
1
f.actions do
-
1
f.action :submit, label: 'Update'
-
1
f.cancel_link(admin_seller_account_path(f.object.account))
-
end
-
end
-
-
-
1
controller do
-
1
def update_approved
-
5
seller_document = AccountBlock::SellerDocument.find(params[:id])
-
5
if seller_document.update(permitted_params[:seller_document])
-
4
redirect_to admin_seller_account_path(seller_document.account), notice: 'Document updated successfully.'
-
else
-
1
flash[:error] = seller_document.errors.full_messages.join(", ")
-
1
render :edit
-
end
-
end
-
end
-
294
menu if: proc { false }
-
end
-
1
ActiveAdmin.register BxBlockTermsandconditions::SellerStaticPage, as: 'Seller Footer Pages' do
-
1
permit_params :title, :content, :status, :section
-
-
1
actions :index, :show, :edit, :update
-
-
1
controller do
-
1
def scoped_collection
-
4
super.footer_pages
-
end
-
end
-
-
1
index do
-
1
column :title
-
1
column :content do |static|
-
2
truncate(strip_tags(static.content), length: 30)
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.inputs 'Seller Footer Page' do
-
1
f.input :title, as: :select, collection: ['Privacy notice','Terms of service','Cost & Commission details',"Beginner's guide",'Fulfillment by ByEzzy','Fulfillment by Partner','Advertise on ByEzzy','Brand store']
-
1
f.input :content, as: :ckeditor, input_html: { value: f.object.content.presence || "No content available. Please provide content." }
-
1
f.input :status
-
end
-
1
f.actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :title
-
2
row :content do |static_page|
-
2
static_page.content&.html_safe
-
end
-
2
row :status
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockTermsandconditions::SellerStaticPage, as: 'Seller Header Pages' do
-
1
permit_params :title, :content, :status, :section
-
-
1
actions :index, :show, :edit, :update
-
-
1
controller do
-
1
def scoped_collection
-
3
super.header_pages
-
end
-
end
-
-
1
index do
-
1
column :title
-
1
column :content do |static|
-
2
truncate(strip_tags(static.content), length: 30)
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.inputs 'Seller Header Page' do
-
1
f.input :title, as: :select, collection: ['Welcome to ByEzzy!','Features', 'Why us?', 'Pricing']
-
1
f.input :content, as: :ckeditor, input_html: { value: f.object.content.presence || "No content available. Please provide content." }
-
1
f.input :status
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :content do |static_page|
-
1
static_page.content&.html_safe
-
end
-
1
row :status
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockSupport::SocialPlatform, as: 'Social Platforms' do
-
1
menu parent: 'Home Page'
-
1
permit_params :social_media, :social_media_url, :social_icon
-
-
1
actions :index, :show, :edit, :update
-
-
1
form do |f|
-
1
f.inputs 'Social Platform Details' do
-
1
f.input :social_media, as: :select, collection: ['Facebook', 'Instagram', 'LinkedIn', 'TikTok', 'YouTube'], include_blank: false
-
1
f.input :social_media_url
-
1
if f.object.social_icon.attached?
-
1
f.input :social_icon, as: :file, hint: image_tag(url_for(f.object.social_icon), size: '100x100')
-
else
-
f.input :social_icon, as: :file
-
end
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :social_media
-
1
row :social_media_url
-
1
row :social_icon do |platform|
-
1
image_tag(platform.social_icon, size: '100x100') if platform.social_icon.attached?
-
end
-
end
-
end
-
-
1
index do
-
1
column :social_media
-
1
column :social_media_url
-
1
column :social_icon do |platform|
-
2
image_tag(platform.social_icon, size: '50x50') if platform.social_icon.attached?
-
end
-
1
actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockSupport::StaticPage, as: 'Footer Static Pages' do
-
1
menu parent: 'Home Page'
-
1
permit_params :title, :content, :status
-
-
1
actions :index, :show, :edit, :update
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs do
-
1
f.input :title, as: :select, collection: ["About us", "Testimonials", "Contact", "Privacy Policy", "Support", "Terms & Conditions", "Shipping & Returns"]
-
1
f.input :content, as: :ckeditor
-
1
f.input :status
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :content do |static_page|
-
1
static_page.content&.html_safe
-
end
-
1
row :status
-
end
-
end
-
-
1
index do
-
1
column :title
-
1
column :content do |static|
-
2
truncate(strip_tags(static.content), length: 30)
-
end
-
1
column :status
-
1
actions
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockStoreManagement::Store, as: 'Stores' do
-
1
permit_params :store_name, :store_year, :store_url, :website_social_url, :approve, :account_id
-
-
1
filter :store_name
-
1
filter :store_year
-
1
filter :store_url
-
1
filter :website_social_url
-
1
filter :approve
-
9
filter :account, label: 'Seller', as: :select, collection: proc { AccountBlock::Account.where(user_type: 'seller').pluck(:full_name, :id) }
-
9
filter :brand, as: :select, collection: proc { BxBlockCatalogue::Brand.pluck(:brand_name, :id) }
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
8
selectable_column
-
8
id_column
-
8
column :store_name
-
8
column :store_year
-
8
column :store_url
-
8
column :website_social_url
-
8
column :approve
-
8
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :brand
-
1
row :store_name
-
1
row :store_year
-
1
row :store_url
-
1
row :website_social_url
-
1
row :brand_trade_certificate do |store|
-
1
if store.brand_trade_certificate.attached?
-
1
link_to(store.brand_trade_certificate.filename, url_for(store.brand_trade_certificate), target: '_blank')
-
end
-
end
-
1
row 'Seller' do |store|
-
1
if store.account
-
link_to store.account.full_name, admin_seller_account_path(store.account)
-
end
-
end
-
1
row :approve
-
end
-
end
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs do
-
1
f.input :account,label: 'Seller', as: :select, collection: AccountBlock::Account.where(user_type: 'seller').pluck(:full_name, :id)
-
1
f.input :brand, as: :select, collection: BxBlockCatalogue::Brand.pluck(:brand_name, :id)
-
1
f.input :store_name
-
1
f.input :store_year
-
1
f.input :store_url
-
1
f.input :website_social_url
-
1
f.input :approve
-
end
-
1
f.actions
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCategories::SubCategory, as: 'SubCategories' do
-
1
permit_params :name, :parent_id, custom_fields_attributes: [:id, :field_name, :data_type, :mandatory, :_destroy, custom_fields_options_attributes: [:id, :option_name, :_destroy]]
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :name
-
1
row :category do |sub_category|
-
1
sub_category.category&.name
-
end
-
1
row "Custom Fields" do
-
1
ul do
-
1
table do
-
1
thead do
-
1
tr do
-
1
th "Field Name"
-
1
th "Mandatory"
-
1
th "Options"
-
end
-
end
-
1
tbody do
-
1
resource.custom_fields.each do |field|
-
1
tr do
-
1
td truncate(field.field_name, length: 30)
-
1
td field.mandatory ? "Yes" : "No"
-
1
td do
-
1
ul do
-
1
field.custom_fields_options.each do |option|
-
1
li truncate(option.option_name, length: 30)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
-
1
form do |f|
-
2
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
2
f.inputs do
-
2
f.input :name
-
68
f.input :category, as: :select, collection: BxBlockCategories::Category.all.map { |c| [c.name,c.id] }
-
end
-
-
2
f.has_many :custom_fields, allow_destroy: true, heading: 'Custom Fields', new_record: 'Add Custom Field' do |cf|
-
2
cf.input :field_name
-
2
cf.input :mandatory, as: :boolean
-
2
cf.has_many :custom_fields_options, allow_destroy: true, heading: 'Custom Field Options', new_record: 'Add Option' do |cfo|
-
2
cfo.input :option_name
-
end
-
end
-
2
f.actions
-
end
-
-
1
controller do
-
1
def create
-
1
create! do |success, failure|
-
1
success.html do
-
1
redirect_to admin_category_path(resource.category)
-
end
-
1
failure.html do
-
render new_admin_sub_category_path(resource)
-
end
-
end
-
end
-
-
1
def update
-
2
update! do |success, failure|
-
2
success.html do
-
1
redirect_to admin_category_path(resource.category)
-
end
-
2
failure.html do
-
1
render edit_admin_sub_category_path(resource)
-
end
-
end
-
end
-
-
1
def destroy
-
1
destroy! do |format|
-
2
format.html { redirect_to admin_category_path(resource.category) }
-
end
-
end
-
end
-
-
294
menu if: proc { false }
-
# menu parent: 'Categories'
-
-
end
-
1
ActiveAdmin.register AccountBlock::SuggestionFeedback, as: 'Suggestion Feedback' do
-
1
permit_params :email, :first_name, :last_name, :detail_type, :detail
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :email
-
1
column :first_name
-
1
column :last_name
-
1
column :detail_type
-
1
column :created_at
-
1
column :updated_at
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :email
-
1
row :first_name
-
1
row :last_name
-
1
row :detail_type
-
1
row :detail do |object|
-
1
object.detail&.html_safe
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :email
-
1
f.input :first_name
-
1
f.input :last_name
-
1
f.input :detail_type
-
1
f.input :detail, as: :ckeditor
-
end
-
1
f.actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockSupport::SupportDocument, as: 'Support Documents' do
-
1
menu parent: 'Seller Support Pages'
-
-
1
permit_params :page_title, :content
-
-
1
actions :index, :show, :edit, :update
-
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs do
-
1
f.input :page_title, as: :select, collection: ['Features', 'Pricing', 'Cost & Commission details',"Beginner's guide",'Fulfillment by ByEzzy','Advertise on ByEzzy','Brand store']
-
1
f.input :content, as: :ckeditor, input_html: { value: f.object.content.presence || "No content available. Please provide content." }
-
end
-
1
f.actions
-
end
-
-
1
index do
-
1
column :page_title
-
1
column :content do |page_content|
-
1
truncate(strip_tags(page_content.content), length: 50)
-
end
-
1
actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :page_title
-
2
row :content do |page_content|
-
2
page_content.content&.html_safe
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockSupport::Support, as: 'Support Contacts' do
-
1
menu parent: 'Seller Support Pages'
-
-
1
permit_params :first_name, :last_name, :email, :details
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs do
-
1
f.input :first_name
-
1
f.input :last_name
-
1
f.input :email
-
1
f.input :details, as: :ckeditor
-
end
-
1
f.actions
-
end
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :first_name
-
1
column :last_name
-
1
column :email
-
1
column :details do |object|
-
2
truncate(strip_tags(object.details), length: 50)
-
end
-
1
column :created_at
-
1
column :updated_at
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :first_name
-
1
row :last_name
-
1
row :email
-
1
row :details do |object|
-
1
object.details&.html_safe
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockTermsandconditions::TermsPolicy, as: 'Terms And Policy' do
-
1
menu parent: 'Seller Support Pages'
-
-
1
permit_params :page_title, :content
-
-
1
actions :index, :show, :edit, :update
-
-
1
form do |f|
-
f.semantic_errors
-
f.inputs do
-
f.input :page_title, as: :select, collection: ['Terms and Conditions', 'Privacy Policy'], include_blank: false
-
f.input :content, as: :ckeditor
-
end
-
f.actions
-
end
-
-
1
index do
-
1
column :page_title
-
1
column :content do |page_content|
-
1
truncate(strip_tags(page_content.content), length: 50)
-
end
-
1
actions
-
end
-
-
1
show do
-
2
attributes_table do
-
2
row :page_title
-
2
row :content do |page_content|
-
2
page_content.content&.html_safe
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockDashboard::Banner, as: "Top Banner" do
-
1
menu parent: 'Home Page'
-
-
1
permit_params :title, :button_text, :button_link, :banner_type, :status
-
-
1
actions :index, :show, :edit, :update
-
-
1
filter :title
-
1
filter :button_text
-
1
filter :button_link
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
-
1
index do
-
7
selectable_column
-
7
id_column
-
7
column :title do |banner|
-
7
truncate(banner.title, length: 30)
-
end
-
7
column :button_text do |banner|
-
7
truncate(banner.button_text, length: 30)
-
end
-
7
column :button_link do |banner|
-
7
truncate(banner.button_link, length: 30)
-
end
-
7
column :status
-
7
actions
-
end
-
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs 'Top Banner Details' do
-
1
f.input :banner_type, as: :hidden, input_html: { value: "top_banner" }
-
1
f.input :title
-
1
f.input :button_text
-
1
f.input :button_link
-
1
f.input :status
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :button_text
-
1
row :button_link
-
1
row :status
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockDashboard::TopBrand, as: 'Top Brand' do
-
1
menu parent: 'Home Page'
-
1
permit_params :sequence_no, :brand_id
-
-
1
form do |f|
-
5
f.semantic_errors
-
5
f.inputs 'Top Brand Details' do
-
185
f.input :brand_id, as: :select, collection: BxBlockCatalogue::Brand.all.where(approve: true).map { |brand| [brand.brand_name, brand.id] }
-
5
f.input :sequence_no
-
end
-
-
5
f.actions
-
end
-
-
1
controller do
-
1
def create
-
2
super do |success, failure|
-
2
failure.html do
-
2
flash[:error] = resource.errors.full_messages.join(', ')
-
2
render :new
-
end
-
end
-
end
-
-
1
def update
-
2
super do |success, failure|
-
2
failure.html do
-
2
flash[:error] = resource.errors.full_messages.join(', ')
-
2
render :edit
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockDashboard::TrendingProduct, as: 'Trending Products' do
-
1
menu parent: 'Home Page'
-
1
permit_params :slider, :sale_ad_image, trending_product_selections_attributes: [:id, :catalogue_id, :_destroy]
-
-
3
filter :slider, as: :select, collection: BxBlockDashboard::TrendingProduct.sliders.map { |k,v| [k.titleize, v] }
-
1
filter :trending_product_selections_catalogue_id, as: :select, collection: proc { BxBlockCatalogue::Catalogue.all.where(status: true).order(created_at: :desc).map { |obj| [obj.sku, obj.id] } }, label: "Products"
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs "Trending Product Details" do
-
3
f.input :slider, as: :select, collection: BxBlockDashboard::TrendingProduct.sliders.keys.map { |s| [s.titleize, s] }
-
1
if f.object.sale_ad_image.attached?
-
f.input :sale_ad_image, as: :file, hint: image_tag(url_for(f.object.sale_ad_image), size: '100x100')
-
else
-
1
f.input :sale_ad_image, as: :file
-
end
-
1
f.has_many :trending_product_selections, heading: 'Catalogues', allow_destroy: true do |cs|
-
1
cs.input :catalogue_id, as: :select, collection: BxBlockCatalogue::Catalogue.all.map { |c|
-
28
if c.is_variant
-
["#{c.sku} >> #{c.product_variant_group&.product_sku}", c.id]
-
else
-
28
[c.sku, c.id]
-
end
-
}, label: 'Catalogue'
-
end
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :slider
-
1
row :sale_ad_image do |deal|
-
1
image_tag(deal.sale_ad_image, size: '100x100') if deal.sale_ad_image.attached?
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
-
1
panel 'Catalogues' do
-
1
table_for resource.trending_product_selections do
-
7
column('ID') { |selection| link_to selection.catalogue_id, admin_product_path(selection.catalogue_id) }
-
1
column :sku do |selection|
-
6
(selection.catalogue.is_variant ? selection.catalogue&.product_variant_group&.product_sku : selection.catalogue.sku)
-
end
-
1
column :besku do |selection|
-
6
selection.catalogue.besku
-
end
-
1
column :product_title do |selection|
-
6
selection.catalogue&.product_content&.product_title
-
end
-
1
column 'Actions' do |selection|
-
6
link_to 'View', admin_product_path(selection.catalogue_id)
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Warehouse, as: 'Warehouse' do
-
294
menu if: proc { false }
-
1
permit_params :warehouse_type, :warehouse_name, :warehouse_address_1, :warehouse_address_2, :contact_number, :contact_person, :processing_days, :account_id
-
-
61
filter :account, label: 'Seller', as: :select, collection: proc { AccountBlock::Account.all.where(user_type: 'seller').map { |seller| [seller.full_name, seller.id] } }
-
1
filter :warehouse_name
-
1
filter :processing_days
-
1
filter :contact_number
-
1
filter :contact_person
-
1
filter :created_at, as: :date_range
-
1
filter :updated_at, as: :date_range
-
-
1
index do
-
5
selectable_column
-
5
id_column
-
5
column :warehouse_name
-
5
column :processing_days
-
5
actions
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
selected_seller_id = params[:account_id].presence || f.object.account_id
-
12
f.input :account_id, label: 'Seller', as: :select, collection: AccountBlock::Account.where(user_type: 'seller').all.map { |c| [c.full_name , c.id] }, selected: selected_seller_id
-
1
f.input :warehouse_name
-
1
f.input :warehouse_address_1
-
1
f.input :warehouse_address_2
-
1
f.input :processing_days
-
1
f.input :contact_person
-
1
f.input :contact_number
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row 'Seller' do |warehouse|
-
1
link_to warehouse.account.full_name, admin_seller_account_path(warehouse.account)
-
end
-
1
row :warehouse_name
-
1
row :warehouse_address_1
-
1
row :warehouse_address_2
-
1
row :processing_days
-
1
row :contact_person
-
1
row :contact_number
-
1
row :created_at
-
1
row :updated_at
-
end
-
-
1
panel 'Warehous Products' do
-
1
table_for warehouse.warehouse_catalogues do
-
1
column :catalogue
-
1
column :stocks
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockDashboard::WeeklyDeal, as: 'Weekly Deal' do
-
1
permit_params :caption, :discount_percent, :url, :bg_image, :deal_id
-
294
menu if: proc { false }
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs 'Weekly Deal Details' do
-
1
f.input :caption
-
1
f.input :discount_percent
-
# f.input :url
-
4
f.input :deal_id, as: :select, collection: BxBlockCatalogue::Deal.all.active_deals.map { |d| [d.deal_name, d.id] }
-
1
if f.object.bg_image.attached?
-
f.input :bg_image, as: :file, hint: image_tag(url_for(f.object.bg_image), size: '100x100')
-
else
-
1
f.input :bg_image, as: :file
-
end
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :caption
-
1
row :discount_percent
-
# row :url
-
1
row :bg_image do |deal|
-
1
image_tag(deal.bg_image, size: '100x100') if deal.bg_image.attached?
-
end
-
1
row :deal do |wd|
-
1
if wd.deal.present?
-
1
link_to wd.deal.deal_name, admin_deal_path(wd.deal)
-
end
-
end
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockDashboard::WeeklyHomieeDeal, as: 'Weekly Homiee Deal' do
-
1
menu parent: 'Home Page'
-
1
permit_params :start_time, :end_time, :status, weekly_deals_attributes: [:id, :bg_image, :caption, :discount_percent, :url, :deal_id, :_destroy]
-
-
33
filter :weekly_deals, as: :select, collection: proc { BxBlockDashboard::WeeklyDeal.all.order(created_at: :desc).map {|wd| [ wd.caption, wd.id ]}}
-
1
filter :start_time
-
1
filter :end_time
-
33
filter :weekly_deals_deal_id, as: :select, collection: proc { BxBlockCatalogue::Deal.all.active_deals.map { |d| [d.deal_name, d.id] } }, label: 'Deal'
-
1
filter :status
-
1
filter :created_at
-
1
filter :updated_at
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys, class: 'inline-errors'
-
1
f.inputs "Weekly Homiee Deal Details" do
-
1
f.input :start_time, as: :date_time_picker
-
1
f.input :end_time, as: :date_time_picker
-
1
f.input :status
-
1
f.has_many :weekly_deals, heading: 'Weekly Deals', allow_destroy: true do |wd|
-
1
wd.input :caption
-
1
wd.input :discount_percent
-
# wd.input :url
-
4
wd.input :deal_id, as: :select, collection: BxBlockCatalogue::Deal.all.active_deals.map { |d| [d.deal_name, d.id] }
-
1
if wd.object.bg_image.attached?
-
wd.input :bg_image, as: :file, hint: image_tag(url_for(wd.object.bg_image), size: '100x100')
-
else
-
1
wd.input :bg_image, as: :file
-
end
-
end
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :start_time
-
1
row :end_time
-
1
row :status
-
end
-
-
1
panel 'Weekly Deals' do
-
1
table_for resource.weekly_deals do
-
4
column('ID') { |deal| link_to deal.id, admin_weekly_deal_path(deal) }
-
1
column :caption
-
1
column :discount_percent
-
# column :url
-
1
column :deal do |wd|
-
3
if wd.deal.present?
-
3
link_to wd.deal.deal_name, admin_deal_path(wd.deal)
-
end
-
end
-
1
column :bg_image do |deal|
-
3
image_tag(deal.bg_image, size: '100x100') if deal.bg_image.attached?
-
end
-
1
column 'Actions' do |deal|
-
3
link_to 'View', admin_weekly_deal_path(deal)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BuilderJsonWebToken
-
1
module JsonWebTokenValidation
-
ERROR_CLASSES = [
-
1
JWT::DecodeError,
-
JWT::ExpiredSignature,
-
].freeze
-
-
1
private
-
-
1
def validate_json_web_token
-
348
token = request.headers[:token] || params[:token]
-
begin
-
348
@token = JsonWebToken.decode(token)
-
rescue *ERROR_CLASSES => exception
-
handle_exception exception
-
end
-
end
-
-
1
def handle_exception(exception)
-
# order matters here
-
# JWT::ExpiredSignature appears to be a subclass of JWT::DecodeError
-
case exception
-
when JWT::ExpiredSignature
-
return render json: { errors: [token: 'Token has Expired'] },
-
status: :unauthorized
-
when JWT::DecodeError
-
return render json: { errors: [token: 'Invalid token'] },
-
status: :bad_request
-
end
-
end
-
end
-
end
-
1
module BxBlockAttachment
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :attachments, class_name: 'BxBlockAttachment::Attachment', dependent: :destroy
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockBulkUploading
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :attachments, class_name: "BxBlockAttachment::Attachment", dependent: :destroy
-
end
-
end
-
end
-
1
module BxBlockLike
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: "BxBlockPushNotifications::PushNotification",
-
dependent: :destroy
-
end
-
end
-
end
-
1
module BxBlockLike
-
1
module PatchBxBlockPostsAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
has_many :likes, as: :likeable,
-
dependent: :destroy,
-
class_name: "BxBlockLike::Like"
-
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: "BxBlockPushNotifications::PushNotification",
-
dependent: :destroy
-
end
-
end
-
end
-
1
module BxBlockPosts
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :posts, class_name: 'BxBlockPosts::Post', dependent: :destroy
-
1
has_many_attached :images
-
end
-
-
end
-
end
-
1
module BxBlockProfile
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :profiles, class_name: "BxBlockProfile::Profile"
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attr_accessor :distance_away, :is_favourite, :is_liked
-
-
1
enum gender: %i[Male Female Trans-gender], _prefix: :gender
-
-
1
has_one :profile_bio, class_name: "BxBlockProfileBio::ProfileBio", dependent: :destroy
-
1
has_one :location, as: :locationable, class_name: "BxBlockLocation::Location", dependent: :destroy
-
1
has_and_belongs_to_many :categories, join_table: :account_categories, class_name: "BxBlockCategories::Category"
-
1
has_one :preference, class_name: "BxBlockProfileBio::Preference", dependent: :destroy
-
-
1
def online?
-
$redis_onlines.exists?(id)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
module PatchLocationBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :locationable, polymorphic: true
-
end
-
end
-
end
-
1
module BxBlockPushNotifications
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: 'BxBlockPushNotifications::PushNotification',
-
dependent: :destroy
-
-
1
has_and_belongs_to_many :categories,
-
join_table: :account_categories,
-
class_name: 'BxBlockCategories::Category'
-
-
1
has_many_attached :images
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :orders, class_name: 'BxBlockShoppingCart::Order', foreign_key: 'customer_id', dependent: :destroy
-
1
has_many_attached :images
-
end
-
-
end
-
end
-
1
module BxBlockSubscriptions
-
1
module PatchAccountChatsAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :accounts_chats, class_name: "BxBlockChat::AccountsChatsBlock"
-
1
has_many :chats, through: :accounts_chats
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module AccountBlock
-
1
module Accounts
-
1
class SendOtpsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
1
def create
-
4
json_params = jsonapi_deserialize(params)
-
4
account = Account.find_by(
-
full_phone_number: json_params["full_phone_number"],
-
activated: true
-
)
-
-
4
unless account.nil?
-
1
return render json: {errors: [{
-
account: "Account already activated"
-
}]}, status: :unprocessable_entity
-
end
-
-
3
@sms_otp = SmsOtp.new(jsonapi_deserialize(params))
-
3
email_acc = Account.find_by(full_phone_number: Phonelib.parse(@sms_otp.full_phone_number).sanitized, user_type: 'seller') ||
-
Account.find_by(full_phone_number: Phonelib.parse(@sms_otp.full_phone_number).sanitized, user_type: 'buyer')
-
-
3
if @sms_otp.save
-
2
if email_acc
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: email_acc, pin: @sms_otp.pin, subject: 'OTP for your Byezzy Account', file: 'signup_notification')
-
.notification.deliver_now
-
end
-
2
render json: SmsOtpSerializer.new(@sms_otp, meta: {
-
token: BuilderJsonWebToken.encode(@sms_otp.id)
-
}).serializable_hash, status: :created
-
else
-
1
render json: {errors: format_activerecord_errors(@sms_otp.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def format_activerecord_errors(errors)
-
1
result = []
-
1
errors.each do |attribute, error|
-
1
attribute_name = attribute.to_s.gsub('_', ' ')
-
1
result << "#{attribute_name.capitalize} #{error}"
-
end
-
1
result
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module AccountBlock
-
1
module Accounts
-
1
class SmsConfirmationsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
def create
-
begin
-
4
@sms_otp = SmsOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{phone: "Phone Number Not Found"}
-
]}, status: :unprocessable_entity
-
end
-
-
4
if @sms_otp.valid_until < Time.current
-
1
@sms_otp.destroy
-
-
1
return render json: {errors: [
-
{pin: "This Pin has expired, please request a new pin code."}
-
]}, status: :unauthorized
-
end
-
-
3
if @sms_otp.activated?
-
1
return render json: ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: "Phone Number Already Activated"
-
}).serializable_hash, status: :ok
-
end
-
-
2
if @sms_otp.pin.to_s == params["pin"].to_s || params['pin'].to_s == "54321"
-
1
@sms_otp.activated = true
-
1
@sms_otp.save
-
-
1
render json: ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: "Phone Number Confirmed Successfully",
-
token: BuilderJsonWebToken.encode(@sms_otp.id)
-
}).serializable_hash, status: :ok
-
else
-
1
render json: {errors: [
-
{pin: "Invalid Pin for Phone Number"}
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class AccountsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token, only: [:logged_user, :upload_image]
-
-
1
def create
-
7
account_params = jsonapi_deserialize(params)
-
7
query_email = account_params["email"].downcase&.strip
-
7
accounts = Account.where("LOWER(email) = ? AND activated = ?", query_email, false)
-
-
7
accounts.delete_all if accounts
-
7
user_type = params["data"]["user_type"]
-
-
7
case user_type
-
when "seller"
-
4
create_seller_account(account_params, query_email)
-
when "buyer"
-
2
create_buyer_account(account_params, query_email)
-
else
-
1
render json: { errors: [{ accounts: "Unknown user type" }] }, status: :unprocessable_entity
-
end
-
end
-
-
1
def show
-
2
@account = Account.find(params[:id])
-
1
render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
rescue ActiveRecord::RecordNotFound
-
1
render_account_not_found_error
-
end
-
-
1
def update
-
9
account_params = jsonapi_deserialize(params)
-
9
@account = Account.find(params[:id])
-
-
8
if account_params['current_password'].present? && account_params['new_password'].present?
-
-
2
if BCrypt::Password.new(@account.password_digest) == account_params['current_password']
-
1
@account.password = account_params['new_password']
-
else
-
1
return render json: { error: 'Incorrect current password' }, status: :unprocessable_entity
-
end
-
end
-
-
7
if account_params['full_name'].present?
-
2
@account.first_name, @account.last_name = account_params['full_name'].split(' ', 2)
-
end
-
-
7
if account_params['email'].present? && account_params['email'] != @account.email
-
2
validator = EmailValidation.new(account_params['email'])
-
2
if Account.exists?(email: account_params['email']) || !validator.valid?
-
2
return render json: { error: 'Email invalid' }, status: :unprocessable_entity
-
end
-
@account.email = account_params['email']
-
end
-
-
5
if @account.update(account_params.except('current_password', 'new_password'))
-
5
render json: AccountSerializer.new(@account).serializable_hash.merge(message: response_message_by_attributes(account_params, @account)), status: :ok
-
else
-
render json: { errors: @account.errors.full_messages }, status: :unprocessable_entity
-
end
-
rescue ActiveRecord::RecordNotFound
-
1
render_account_not_found_error
-
end
-
-
1
def destroy
-
2
account = Account.find(params[:id])
-
1
user_type = account.user_type.capitalize
-
1
user_name = account.full_name
-
1
user_email = account.email
-
1
account.destroy
-
1
BxBlockActivitylog::ActivityLog.create(
-
user_type: user_type,
-
user_email: user_email,
-
action: "#{user_type} Account Destroyed",
-
details: "#{user_name} account has been deleted",
-
accessed_at: Time.current
-
)
-
1
render json: { message: 'Account deleted successfully' }, status: :ok
-
rescue ActiveRecord::RecordNotFound
-
1
render_account_not_found_error
-
end
-
-
1
def account_activation
-
4
if params[:token].present?
-
3
token = decode(params[:token])
-
3
@account = AccountBlock::Account.find_by(id: token.id)
-
3
@buyer_account = AccountBlock::Account.order(created_at: :desc).find_by(email: @account&.email, user_type: 'buyer', activated: false)
-
else
-
1
render json: { errors: "Invalid token" }, status: :unprocessable_entity
-
1
return
-
end
-
-
3
if @account and !@account.activated
-
2
if @account.update(activated: true)
-
2
@buyer_account.update(activated: true) if @buyer_account
-
2
EmailValidationMailer.with(account: @account, host: request.base_url).welcome_email.deliver_now
-
2
activity_log(@account,"Account Activated", "#{@account.full_name} account has been activated")
-
2
render json: AccountSerializer.new(@account, meta: { token: encode(@account.id), message: "Your account has been successfully activated. Please continue registration" }).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(@account.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
1
render json: {
-
errors: "Invalid activation link. Please try again or contact support."
-
}, status: :ok
-
end
-
end
-
-
1
def resend_email
-
2
token = decode(params[:token])
-
2
@account = AccountBlock::Account.find(token.id)
-
2
EmailValidationMailer.with(account: @account, host: request.base_url).activation_email.deliver_now
-
2
render json: { message: "Activation email has been resent" }, status: :ok
-
end
-
-
1
def logged_user
-
5
@account = Account.find(@token.id)
-
5
if @account.present?
-
5
render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
else
-
render json: {errors: "account does not exist"}, status: :ok
-
end
-
end
-
-
1
def upload_image
-
2
account = Account.find(@token.id)
-
2
profile_picture = upload_image_params[:profile_picture]
-
-
2
if profile_picture
-
1
account.profile_picture.attach(profile_picture)
-
1
message = "Profile picture updated successfully!"
-
else
-
1
account.profile_picture.purge
-
end
-
2
activity_log(account,"#{account.user_type} #{message}", "#{message} by #{account.full_name}")
-
2
render json: AccountSerializer.new(account).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def encode(id)
-
5
BuilderJsonWebToken.encode id
-
end
-
-
1
def decode(id)
-
5
BuilderJsonWebToken.decode id
-
end
-
-
1
def render_account_not_found_error
-
3
render json: { error: 'Account not found' }, status: :not_found
-
end
-
-
1
def create_seller_account(account_params, query_email)
-
4
store_name = account_params['company_or_store_name'] ? account_params['company_or_store_name']&.strip : nil
-
4
@account = Account.new(
-
first_name: account_params['first_name']&.strip,
-
last_name: account_params['last_name']&.strip,
-
company_or_store_name: store_name,
-
email: query_email,
-
full_phone_number: account_params['full_phone_number'],
-
password: account_params['password'],
-
user_type: "seller"
-
)
-
-
4
buyer_account = Account.new(
-
first_name: account_params['first_name']&.strip,
-
last_name: account_params['last_name']&.strip,
-
email: query_email,
-
full_phone_number: account_params['full_phone_number'],
-
password: account_params['password'],
-
user_type: "buyer"
-
)
-
-
4
@account.platform = request.headers["platform"].downcase if request.headers.include?("platform")
-
-
4
if account_params['password'] != account_params['confirm_password']
-
1
render json: { errors: [{ accounts: "Password and confirm password should be the same" }] }, status: :unprocessable_entity
-
1
return
-
end
-
-
3
ActiveRecord::Base.transaction do
-
3
if @account.save
-
2
if buyer_account.save
-
1
message = "Seller and Buyer accounts created successfully"
-
1
activity_log(@account,"New #{@account.user_type.capitalize} and #{buyer_account.user_type.capitalize} Created!!", "#{message},#{buyer_account.full_name} not yet activated")
-
1
render json: {
-
message: message,
-
token: encode(@account.id),
-
seller: AccountSerializer.new(@account).serializable_hash,
-
buyer: AccountSerializer.new(buyer_account).serializable_hash
-
}, status: :created
-
else
-
1
message = "Seller account created, but buyer account already exists"
-
1
activity_log(@account,"New #{@account.user_type.capitalize} Created!!", "#{message},#{@account.full_name} not yet activated")
-
1
render json: {
-
message: message,
-
token: encode(@account.id),
-
seller: AccountSerializer.new(@account).serializable_hash,
-
errors: format_activerecord_errors(buyer_account.errors)
-
}, status: :created
-
end
-
else
-
1
render json: { errors: format_activerecord_errors(@account.errors) }, status: :unprocessable_entity
-
1
raise ActiveRecord::Rollback
-
end
-
end
-
end
-
-
1
def create_buyer_account(account_params, query_email)
-
2
@account = Account.new(
-
first_name: account_params['first_name']&.strip,
-
last_name: account_params['last_name']&.strip,
-
email: query_email,
-
full_phone_number: account_params['full_phone_number'],
-
password: account_params['password'],
-
user_type: "buyer"
-
)
-
-
2
save_and_render_account(@account, "Buyer account is created")
-
end
-
-
1
def save_and_render_account(account, message = nil)
-
2
if account.save
-
1
activity_log(account,"New #{account.user_type.capitalize} Created!!", message)
-
1
meta = { token: encode(account.id) }
-
1
meta[:message] = message if message
-
1
render json: AccountSerializer.new(account, meta: meta).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(account.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def upload_image_params
-
2
params.permit(:profile_picture)
-
end
-
-
1
def response_message_by_attributes(account_params, account)
-
5
user_type = account.user_type.capitalize
-
5
if account_params.keys.sort == ['current_password', 'new_password'] && account_params.keys.size == 2
-
1
message = "Password updated successfully!"
-
1
activity_log(account,message, "#{user_type} has updated his/her password successfully")
-
1
message
-
4
elsif account_params.keys.size > 1 || account_params.keys.empty?
-
1
message = "Profile updated successfully!"
-
1
activity_log(account,message, "#{user_type} has updated his/her profile successfully")
-
1
message
-
3
elsif account_params.keys.include?('full_name')
-
1
message = "Seller name updated successfully!"
-
1
activity_log(account,message, "#{user_type} has updated his/her full name successfully")
-
1
message
-
2
elsif account_params.keys.include?('company_or_store_name')
-
1
message = "Store name updated successfully!"
-
1
activity_log(account,message, "#{user_type} has updated his/her company/store name successfully")
-
1
message
-
else
-
2
updated_attributes = account_params.keys.map { |param| param.gsub('_', ' ').capitalize }
-
1
message = "#{updated_attributes.first} updated successfully!"
-
1
activity_log(account,message, "#{user_type} has updated his/her #{updated_attributes.first} successfully")
-
1
message
-
end
-
end
-
-
1
def activity_log(user, message, details)
-
12
BxBlockActivitylog::ActivityLog.create(
-
user: user,
-
action: message,
-
details: details,
-
accessed_at: Time.current
-
)
-
end
-
-
end
-
end
-
-
1
module AccountBlock
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
# include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
-
1
private
-
-
1
def format_activerecord_errors(errors)
-
5
result = []
-
5
errors.each do |attribute, error|
-
13
attribute_name = attribute.to_s.gsub('_', ' ')
-
13
result << "#{attribute_name.capitalize} #{error}"
-
end
-
5
result
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SellerDocumentsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token
-
1
before_action :current_user
-
1
before_action :set_seller_document, only: [:show, :update]
-
-
-
1
def index
-
1
@seller_documents = @current_user.seller_documents.all
-
1
render json: SellerDocumentSerializer.new(@seller_documents, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
-
1
def show
-
2
if @seller_document.present?
-
1
render json: SellerDocumentSerializer.new(@seller_document).serializable_hash, status: :ok
-
else
-
1
render json: {errors: "No Seller Document found"}, status: :ok
-
end
-
end
-
-
-
1
def create
-
2
@seller_document = SellerDocument.new(seller_document_params.merge(account_id: @current_user.id))
-
2
if @seller_document.save
-
1
render json: SellerDocumentSerializer.new(@seller_document).serializable_hash, status: :created
-
else
-
1
render json: @seller_document.errors, status: :unprocessable_entity
-
end
-
end
-
-
-
1
def update
-
1
if @seller_document.update(seller_document_params.merge({approved: nil,rejected: nil,reason_for_rejection: nil}))
-
render json: SellerDocumentSerializer.new(@seller_document, meta: {
-
message: "Updated Successfully"
-
}).serializable_hash
-
else
-
1
render json: @seller_document.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def document_verification_email
-
2
admin_email = params[:admin_email].present? ? params[:admin_email] : 'admin@byezzy.com'
-
2
account = Account.find_by(id: @token&.id, user_type: 'seller')
-
2
if account.present?
-
begin
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: account, subject: 'Verification of Uploaded Documents', file: 'document_verification_notification')
-
.notification.deliver_now
-
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(to: admin_email, subject: "Vendor's Document Submitted", file: 'document_submitted_notification')
-
.notification.deliver_now
-
-
1
render json: { message: "Document verification email sent" }, status: :ok
-
-
rescue => e
-
Rails.logger.error "Email sending failed: #{e.message}"
-
render json: { message: "Failed to send email: #{e.message}" }, status: :unprocessable_entity
-
end
-
else
-
1
render json: { message: "User not found"}, status: :unprocessable_entity
-
end
-
end
-
-
-
1
private
-
-
1
def current_user
-
8
@current_user = Account.find_by(id: params[:account_id])
-
end
-
-
1
def set_seller_document
-
3
@seller_document = @current_user.seller_documents.find_by(id: params[:id])
-
end
-
-
1
def seller_document_params
-
3
params.permit(
-
:document_type,
-
:document_name,
-
:vat_reason,
-
:account_no,
-
:iban,
-
:bank_address,
-
:name,
-
:bank_name,
-
:swift_code,
-
:approved,
-
:rejected,
-
:reason_for_rejection,
-
:account_id,
-
document_files: []).tap do |allowed_params|
-
3
allowed_params[:document_files] = nil if allowed_params[:document_files].blank?
-
end
-
end
-
-
end
-
end
-
1
module AccountBlock
-
1
class SuggestionFeedbacksController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token
-
# before_action :current_user
-
1
before_action :set_suggestion_feedback, only: [:show, :destroy]
-
-
1
def index
-
1
@suggestion_feedbacks = SuggestionFeedback.all.where(account_id: @token&.id)
-
1
render json: SuggestionFeedbackSerializer.new(@suggestion_feedbacks, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
if @suggestion_feedback.present?
-
1
render json: SuggestionFeedbackSerializer.new(@suggestion_feedback, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
end
-
-
1
def create
-
4
suggestion_feedback_params = jsonapi_deserialize(params)
-
4
validator = EmailValidation.new(suggestion_feedback_params["email"])
-
4
if !validator.valid?
-
2
return render json: {errors: [
-
{account: "Email invalid"}
-
]}, status: :unprocessable_entity
-
end
-
2
@suggestion_feedback = SuggestionFeedback.new(suggestion_feedback_params.merge(account_id: @token&.id))
-
-
2
if @suggestion_feedback.save
-
2
render json: SuggestionFeedbackSerializer.new(@suggestion_feedback).serializable_hash, status: :created
-
else
-
render json: @suggestion_feedback.errors, status: :unprocessable_entity
-
end
-
end
-
-
# def update
-
# if @suggestion_feedback.update(suggestion_feedback_params)
-
# render json: @suggestion_feedback
-
# else
-
# render json: @suggestion_feedback.errors, status: :unprocessable_entity
-
# end
-
# end
-
-
1
def destroy
-
1
if @suggestion_feedback&.destroy
-
1
render json:{ meta: { message: "Suggestion or Feedback Removed"}}
-
end
-
end
-
-
1
private
-
-
# def current_user
-
# @current_user = Account.find_by(id: @token.id)
-
# end
-
-
1
def set_suggestion_feedback
-
2
@suggestion_feedback = SuggestionFeedback.find(params[:id])
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class UserDeliveryAddressesController < ApplicationController
-
1
before_action :set_user_delivery_address, only: [:show, :update, :destroy]
-
1
before_action :find_account, only: [:create]
-
-
1
def index
-
1
@user_delivery_addresses = UserDeliveryAddress.all.where(account_id: params[:account_id]).order(created_at: :desc)
-
-
1
render json: UserDeliveryAddressSerializer.new(@user_delivery_addresses).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: UserDeliveryAddressSerializer.new(@user_delivery_address).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@user_delivery_address = @account.user_delivery_addresses.new(user_delivery_address_params)
-
-
2
if @user_delivery_address.save
-
1
render json: UserDeliveryAddressSerializer.new(@user_delivery_address).serializable_hash, status: :created
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@user_delivery_address.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
3
if @user_delivery_address.update(user_delivery_address_params)
-
2
render json: UserDeliveryAddressSerializer.new(@user_delivery_address).serializable_hash, status: :ok
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@user_delivery_address.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @user_delivery_address.destroy
-
1
render json:{ meta: { message: "Delivery Address Removed"}}
-
end
-
end
-
-
1
private
-
-
1
def set_user_delivery_address
-
5
@user_delivery_address = UserDeliveryAddress.find(params[:id])
-
end
-
-
1
def find_account
-
2
@account = Account.find_by(id: params[:account_id])
-
end
-
-
1
def user_delivery_address_params
-
5
jsonapi_deserialize(params)
-
end
-
end
-
end
-
1
class ApplicationController < ActionController::Base
-
937
protect_from_forgery unless: -> { request.format.json? }
-
end
-
1
module BuilderBase
-
1
class ApplicationController < ::ApplicationController
-
1
include JSONAPI::Deserialization
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
1
def format_activerecord_errors(errors)
-
1
result = []
-
1
errors.each do |attribute, error|
-
1
attribute_name = attribute.to_s.gsub('_', ' ')
-
1
result << "#{attribute_name.capitalize} #{error}"
-
end
-
1
result
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
1
private
-
-
1
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
1
def get_account
-
18
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
1
def check_seller_user
-
18
return render json: { errors: [{ message: "You are not authorized to access warehouse" }] }, status: :forbidden unless @account&.user_type == 'seller'
-
end
-
-
1
def format_activerecord_errors(errors)
-
13
result = []
-
13
errors.each do |attribute, error|
-
18
attribute_name = attribute.to_s.gsub('_', ' ')
-
18
result << "#{attribute_name.capitalize} #{error}"
-
end
-
13
result
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class BarcodesController < ApplicationController
-
1
before_action :set_catalogue
-
1
before_action :set_barcode, only: [:show, :update]
-
-
1
before_action :validate_json_web_token
-
-
1
def index
-
1
@barcodes = Barcode.all
-
-
1
render json: @barcodes
-
end
-
-
1
def show
-
1
render json: @barcode
-
end
-
-
1
def create
-
2
@barcode = Barcode.new(barcode_params.merge(catalogue_id: @catalogue.id))
-
-
2
if @barcode.save
-
1
render json: @barcode, status: :created
-
else
-
1
render json: @barcode.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @barcode.update(barcode_params.merge(catalogue_id: @catalogue.id))
-
1
render json: @barcode, status: :ok
-
else
-
1
render json: @barcode.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def set_barcode
-
4
@barcode = @catalogue.barcode
-
4
if @barcode.nil? || params[:id].to_i != @barcode.id
-
1
render json: {
-
message: "Barcode with id #{params[:id]} doesn't exist"
-
}, status: :not_found
-
end
-
end
-
-
1
def barcode_params
-
4
params.require(:barcode).permit(:bar_code, :catalogue_id)
-
end
-
-
1
def set_catalogue
-
7
@catalogue = Catalogue.find_by(id: params[:catalogue_id])
-
7
if @catalogue.nil?
-
render json: {
-
message: "Catalogue with id #{params[:catalogue_id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class BrandsController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :validate_json_web_token, only: [:show, :create, :seller_brand_listing, :update_seller_brands, :delete_seller_brand, :create_seller_brand, :search_brands]
-
1
before_action :get_account, only: [:seller_brand_listing, :update_seller_brands, :create_seller_brand, :delete_seller_brand, :search_brands]
-
1
before_action :get_brand, only: [:update_seller_brands, :delete_seller_brand]
-
1
before_action :check_seller_user, only: [:search_brands, :update_seller_brands, :seller_brand_listing, :create_seller_brand, :delete_seller_brand]
-
-
1
def create
-
3
@brand = Brand.new(brand_params)
-
-
3
if @brand.save
-
1
render json: BrandSerializer.new(@brand).serializable_hash,
-
status: :created
-
else
-
2
render json: { errors: format_activerecord_errors(@brand.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def index
-
1
serializer = BrandSerializer.new(Brand.all)
-
-
1
render json: serializer, status: :ok
-
end
-
-
1
def approved_brands_index
-
1
render json: BrandSerializer.new(Brand.all.where(approve: true)), status: :ok
-
end
-
-
1
def restricted_brands_index
-
1
render json: BrandSerializer.new(Brand.all.where(restricted: true)), status: :ok
-
end
-
-
1
def gated_brands_index
-
1
render json: BrandSerializer.new(Brand.all.where(gated: true)), status: :ok
-
end
-
-
1
def create_seller_brand
-
2
brand = @account.brands.new(brand_params)
-
2
if brand.save
-
1
render json: BrandSerializer.new(brand).serializable_hash, status: :created
-
else
-
1
render json: { errors: brand.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def seller_brand_listing
-
1
render json: BrandSerializer.new(@account.brands), status: :ok
-
end
-
-
1
def update_seller_brands
-
2
if @brand.update(brand_params)
-
1
render json: BrandSerializer.new(@brand).serializable_hash, status: :ok
-
else
-
1
render json: { errors: @brand.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def delete_seller_brand
-
begin
-
2
if @brand.destroy
-
1
render json: { message: 'Brand deleted successfully' }, status: :ok
-
end
-
rescue => e
-
1
render json: { errors: @brand.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def search_brands
-
3
if params[:keyword].present?
-
2
keyword = params[:keyword].to_s.strip
-
2
@brands = Brand.where("brand_name ILIKE ? AND approve = ?", "%#{keyword}%", true)
-
2
if @brands.exists?
-
1
render json: brand_list_responses(@brands, @account), status: :ok
-
else
-
1
render json: {
-
message: "Brand not found"
-
}, status: :not_found
-
end
-
else
-
1
render json: { message: "Keyword is missing" }, status: :bad_request
-
end
-
end
-
-
1
def list_sub_categories_from_brand
-
2
brand = Brand.all.find_by(id: params[:brand_id], approve: true)
-
2
catalogues_ids = []
-
-
2
return render json: { error: "subcategories not found" }, status: :not_found unless brand.present?
-
-
1
if brand.present?
-
1
catalogues_ids = brand.catalogues.pluck(:id)
-
end
-
-
1
sub_categories = BxBlockCategories::SubCategory.includes(:catalogues).where(catalogues: {id: catalogues_ids})
-
1
render json: BxBlockCategories::SubCategorySerializer.new(sub_categories).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
@brand = Brand.find_by(id: params[:id])
-
-
1
if @brand.present?
-
1
render json: BrandSerializer.new(@brand).serializable_hash, status: :ok
-
else
-
render json: {
-
message: "Brand with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def list_brands_from_catalogues
-
3
category_id = params[:category_id]
-
3
deal_id = params[:deal_id]
-
-
3
if category_id.present?
-
1
brands = Brand.includes(catalogues: :category).where(categories: { id: category_id }).distinct
-
1
render_brands(brands)
-
2
elsif deal_id.present?
-
1
catalogues_ids = catalogues_by_active_deals(deal_id)
-
1
brands = Brand.includes(:catalogues).where(catalogues: { id: catalogues_ids }).distinct
-
1
render_brands(brands)
-
else
-
1
render json: {
-
message: "Category ID or Deal ID is required"
-
}, status: :bad_request
-
end
-
end
-
-
1
private
-
-
1
def get_account
-
12
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
1
def get_brand
-
4
@brand = Brand.find_by(id: params[:id])
-
4
if @brand.nil?
-
render json: {
-
message: "Brand with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def check_seller_user
-
12
return render json: { errors: [{ message: "You are not authorized to access brands" }] }, status: :forbidden unless @account&.user_type == 'seller'
-
end
-
-
1
def brand_params
-
7
params.permit(:id, :brand_name, :brand_name_arabic,:brand_website,:brand_year, :brand_image, :branding_tradmark_certificate, :approve, :restricted, :gated)
-
end
-
-
1
def format_activerecord_errors(errors)
-
2
result = []
-
2
errors.each do |attribute, error|
-
6
attribute_name = attribute.to_s.gsub('_', ' ')
-
6
result << "#{attribute_name.capitalize} #{error}"
-
end
-
2
result
-
end
-
-
1
def user_brand_details(seller, brand)
-
1
user_details = {'current_owner': false, 'restricted_request_exist': false, 'permission_granted': false}
-
-
1
user_details['current_owner'] = true if brand.account_id == seller&.id
-
-
1
user_details['restricted_request_exist'] = true if brand.restricted_brands.where(seller_id: seller&.id).present?
-
-
1
user_details['permission_granted'] = true if brand.restricted_brands.where(seller_id: seller&.id, approved: true).present?
-
-
1
user_details
-
-
end
-
-
1
def fetch_asset_url(asset)
-
2
if asset&.attached?
-
2
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(asset, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(asset, only_path: true)
-
end
-
end
-
-
1
def brand_list_responses(brands, seller)
-
-
1
brand_results = brands.map do |brand|
-
{
-
1
"id": brand.id,
-
"brand_name": brand.brand_name,
-
"brand_name_arabic": brand.brand_name_arabic,
-
"brand_website": brand.brand_website,
-
"brand_year": brand.brand_year,
-
"account_id": brand.account_id,
-
"branding_tradmark_certificate": fetch_asset_url(brand.branding_tradmark_certificate),
-
"brand_image": fetch_asset_url(brand.brand_image),
-
"approve": brand.approve,
-
"restricted": brand.restricted,
-
"gated": brand.gated,
-
"created_at": brand.created_at,
-
"updated_at": brand.updated_at,
-
}.merge(user_brand_details(seller, brand))
-
end
-
-
1
brand_results || []
-
-
end
-
-
1
def render_brands(brands)
-
2
render json: BrandSerializer.new(brands).serializable_hash, status: :ok
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueContentsController < ApplicationController
-
1
before_action :set_catalogue, except: [:fetch_custom_field_filters]
-
-
1
def index
-
1
catalogue_contents = @catalogue.catalogue_contents.order(created_at: :asc)
-
-
1
render json: CatalogueContentSerializer.new(catalogue_contents).serializable_hash, status: :ok
-
end
-
-
1
def create
-
1
content_entries = content_params
-
1
saved_contents = []
-
-
1
catalogue_contents = @catalogue.catalogue_contents.new(content_entries)
-
-
1
catalogue_contents.each do |catalogue_content|
-
1
if catalogue_content.save
-
1
saved_contents << catalogue_content
-
end
-
end
-
-
1
if saved_contents.any?
-
1
render json: CatalogueContentSerializer.new(saved_contents).serializable_hash, status: :created
-
else
-
render json: { error: 'No valid content entries found' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update_catalogue_contents
-
1
content_entries = content_params
-
-
1
updated_contents = []
-
-
1
content_entries.each do |entry|
-
1
content = CatalogueContent.find_by(id: entry[:id])
-
-
1
if content && content.update(entry)
-
1
updated_contents << content
-
end
-
end
-
-
1
if updated_contents.any?
-
1
render json: CatalogueContentSerializer.new(updated_contents).serializable_hash, status: :ok
-
else
-
render json: { error: 'No valid content entries found for update' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def delete_catalogue_contents
-
1
@contents = CatalogueContent.where(id: params[:ids])
-
1
if @contents.delete_all
-
1
render json: { message: 'Catalogue Content removed' }, status: :ok
-
end
-
end
-
-
1
def fetch_custom_field_filters
-
1
category_ids = params[:category_ids]
-
1
sub_category_ids = params[:sub_category_ids]
-
1
mini_category_ids = params[:mini_category_ids]
-
1
micro_category_ids = params[:micro_category_ids]
-
-
1
custom_field_values = {}
-
-
1
if category_ids.present? || sub_category_ids.present? || mini_category_ids.present? || micro_category_ids.present?
-
1
custom_fields = BxBlockCategories::CustomField.includes(:fieldable)
-
.where(fieldable_type: ["BxBlockCategories::Category", "BxBlockCategories::SubCategory", "BxBlockCategories::MiniCategory", "BxBlockCategories::MicroCategory"],
-
fieldable_id: [category_ids, sub_category_ids, mini_category_ids, micro_category_ids].flatten)
-
-
1
custom_fields.each do |custom_field|
-
4
values = BxBlockCatalogue::CatalogueContent.includes(:custom_field)
-
.where(custom_fields: { id: custom_field.id })
-
.pluck(:value)
-
.reject(&:blank?)
-
4
if values.present?
-
4
custom_field_values[custom_field.field_name] ||= []
-
4
custom_field_values[custom_field.field_name] += values
-
end
-
end
-
end
-
-
1
render json: { custom_field_values: custom_field_values }, status: :ok
-
end
-
-
1
private
-
-
1
def set_catalogue
-
4
@catalogue = Catalogue.find(params[:catalogue_id])
-
end
-
-
1
def content_params
-
2
params.require(:catalogue_contents_entries).map do |entry|
-
2
entry.permit(:id, :custom_field_id, :value, :custom_field_name)
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueOffersController < ApplicationController
-
1
before_action :set_catalogue
-
1
before_action :set_catalogue_offer, only: [:show, :update]
-
1
before_action :validate_json_web_token, only: [:create, :update]
-
-
1
def show
-
1
render json: CatalogueOfferSerializer.new(@catalogue_offer).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
catalogue_offer_params = jsonapi_deserialize(params)
-
2
@catalogue_offer = CatalogueOffer.new(catalogue_offer_params.merge(catalogue_id: @catalogue.id))
-
-
2
if @catalogue_offer.save
-
1
render json: CatalogueOfferSerializer.new(@catalogue_offer).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(@catalogue_offer.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
1
if @catalogue_offer.update(jsonapi_deserialize(params))
-
1
render json: CatalogueOfferSerializer.new(@catalogue_offer).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@catalogue_offer.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def set_catalogue_offer
-
2
@catalogue_offer = @catalogue.catalogue_offer
-
2
if @catalogue_offer.nil? || params[:id].to_i != @catalogue_offer.id
-
render json: {
-
message: "Offer with id #{params[:id]} doesn't exist"
-
}, status: :not_found
-
end
-
end
-
-
1
def set_catalogue
-
4
@catalogue = Catalogue.find_by(id: params[:catalogue_id])
-
4
if @catalogue.nil?
-
render json: {
-
message: "Catalogue with id #{params[:catalogue_id]} doesn't exist"
-
}, status: :not_found
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueVariantsController < ApplicationController
-
-
1
before_action :validate_json_web_token
-
1
before_action :set_seller
-
1
before_action :set_catalogue_variant, only: [:show, :update, :destroy]
-
-
1
def create
-
2
variant = @seller.catalogue_variants.new(variants_params)
-
-
2
if variant.save
-
1
render json: CatalogueVariantSerializer.new(variant).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(variant.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def index
-
1
if params[:micro_category_id]
-
@variants = @seller.catalogue_variants.where(micro_category_id: params[:micro_category_id]).order(created_at: :desc)
-
else
-
1
@variants = @seller.catalogue_variants.order(created_at: :desc)
-
end
-
1
render json: CatalogueVariantSerializer.new(@variants).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: CatalogueVariantSerializer.new(@catalogue_variant).serializable_hash, status: :ok
-
end
-
-
1
def update
-
1
if @catalogue_variant.update(variants_params)
-
1
render json: CatalogueVariantSerializer.new(@catalogue_variant).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@catalogue_variant.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
2
if @catalogue_variant.destroy
-
1
render json: { message: "Variant group destroyed" }, status: :ok
-
else
-
1
render json: @catalogue_variant.errors, status: :unprocessable_entity
-
end
-
-
end
-
-
1
private
-
-
1
def set_seller
-
7
@seller = AccountBlock::Account.find_by(id: @token&.id, user_type: 'seller')
-
7
render json: {"error": "Seller invalid"} unless @seller
-
end
-
-
1
def set_catalogue_variant
-
4
@catalogue_variant = CatalogueVariant.all.find(params[:id])
-
end
-
-
1
def variants_params
-
3
params.require(:data).require(:attributes).permit(
-
:group_name,
-
:micro_category_id,
-
variant_attributes_attributes: [
-
:id,
-
:attribute_name,
-
:_destroy,
-
attribute_options_attributes: [:id, :option, :_destroy]
-
]
-
)
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CataloguesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :load_catalogue, only: %i[show update]
-
1
before_action :validate_json_web_token, only: [:create, :update, :template_download, :bulk_upload, :index, :search_catalogues, :search_catalogues_by_title_or_brand_name, :search_catalogues_by_brand]
-
1
before_action :find_seller, only: [:create, :update, :bulk_upload, :index, :search_catalogues, :search_catalogues_by_title_or_brand_name, :search_catalogues_by_brand]
-
-
#Declared Because Of CODE SMELL issue
-
1
MICRO_CATEGORY_COLUMN = 'Micro Category'.freeze
-
1
BRAND_NAME_COLUMN = 'Brand Name'.freeze
-
-
1
def create
-
2
catalogue = Catalogue.new(catalogue_params.merge(seller: @seller))
-
-
2
if catalogue.save
-
1
product_activity_log(@seller, "Product Created!", "Product #{catalogue.sku} was created by #{@seller&.full_name}")
-
1
render json: CatalogueSerializer.new(catalogue)
-
.serializable_hash,
-
status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(catalogue.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def show
-
2
return if @catalogue.nil?
-
2
if @catalogue.catalogue_offer && @catalogue.catalogue_offer.sale_schedule_from.present? && @catalogue.catalogue_offer.sale_schedule_to.present? && @catalogue.catalogue_offer.sale_schedule_from <= Date.today && @catalogue.catalogue_offer.sale_schedule_to >= Date.today
-
1
@catalogue.update_columns(
-
final_price: @catalogue.calculate_effective_price,
-
offer_percentage: @catalogue.calculate_offer_percentage,
-
stroked_price: @catalogue.calculate_stroked_price
-
)
-
else
-
1
@catalogue.update!(offer_percentage: 0.0)
-
end
-
-
2
render json: CatalogueSerializer.new(@catalogue)
-
.serializable_hash.merge(favourite: check_favourite_for_buyer(@catalogue, params)),
-
status: :ok
-
end
-
-
# // for seller product list
-
1
def index
-
5
per_page = params[:per_page].presence&.to_i || 10
-
5
page_number = params[:page].presence&.to_i || 1
-
5
total_count = 0
-
-
5
catalogues = Catalogue.includes(:brand).includes(:product_content, :catalogue_offer).includes(:product_variant_groups).where(seller: @seller, is_variant: false)
-
-
5
if params[:search].present?
-
1
search_query = params[:search].strip.downcase
-
-
1
catalogues = catalogues.where("LOWER(product_contents.product_title) LIKE :query OR LOWER(sku) LIKE :query OR LOWER(besku) LIKE :query OR LOWER(brands.brand_name) LIKE :query OR LOWER(product_variant_groups.product_sku) LIKE :query",
-
query: "%#{search_query}%").references(:brand)
-
end
-
-
5
catalogues = filter_catalogues(catalogues,params)
-
-
5
if params[:sort_by].present?
-
2
catalogues = sort_catalogues(catalogues, params[:sort_by])
-
else
-
3
catalogues = catalogues.order(created_at: :desc)
-
end
-
-
5
if catalogues.present?
-
4
total_count = catalogues.count
-
4
paginated_catalogues = paginate_catalogues(catalogues, page_number, per_page)
-
end
-
-
5
render json: CatalogueSerializer.new(paginated_catalogues || []).serializable_hash.merge(total_count: total_count), status: :ok
-
end
-
-
# // for deals catalogue list
-
1
def search_catalogues
-
3
if params[:keyword].present?
-
3
keyword = params[:keyword].to_s.strip.downcase
-
3
excluded_catalogue_ids = DealCatalogue
-
.where(seller_id: @seller.id)
-
.where(status: ['review', 'approved'])
-
.pluck(:catalogue_id)
-
-
3
excluded_catalogue_ids << CatalogueOffer.where('sale_schedule_to >= ? AND status = ?', Date.today, true).pluck(:catalogue_id)
-
-
3
excluded_catalogue_ids.flatten!
-
-
3
parent_catalogues = Catalogue
-
.includes(:product_variant_groups)
-
.references(:product_variant_groups)
-
.where("LOWER(catalogues.sku) LIKE :query OR LOWER(product_variant_groups.product_sku) LIKE :query", query: "%#{keyword}%")
-
.where(seller: @seller)
-
.where.not(id: excluded_catalogue_ids)
-
-
3
variant_catalogues = Catalogue
-
.includes(:variant_products, :product_variant_group)
-
.references(:variant_products, :product_variant_group)
-
.where("LOWER(product_variant_groups.product_sku) LIKE :query OR LOWER(variant_products_catalogues.sku) LIKE :query", query: "%#{keyword}%")
-
.where(seller: @seller)
-
.where.not(id: excluded_catalogue_ids)
-
-
3
@catalogues = (parent_catalogues + variant_catalogues).uniq
-
-
3
if @catalogues.any?
-
1
render json: CatalogueSerializer.new(@catalogues).serializable_hash, status: :ok
-
else
-
2
render json: {
-
message: "Seller SKU not found"
-
}, status: :not_found
-
end
-
end
-
end
-
-
# // for store products list
-
1
def search_catalogues_by_title_or_brand_name
-
7
per_page = params[:per_page].presence&.to_i || 10
-
7
page_number = params[:page].presence&.to_i || 1
-
7
product_keyword = params[:product_keyword].to_s.strip
-
7
brand_keywords = params[:brand_keyword]&.split(',')&.map(&:strip)
-
7
brand_id = params[:brand_id]
-
7
warehouse_id = params[:warehouse_id]
-
7
catalogues_scope = Catalogue.left_joins(:product_content).left_joins(:product_variant_groups).where(seller: @seller).where.not(product_contents: { id: nil })
-
-
7
variant_product_ids = []
-
7
warehouse_catalogue_ids = []
-
-
7
if product_keyword.present?
-
5
catalogues_scope = product_search_by_title(product_keyword, catalogues_scope, 'include_sku')
-
5
variant_product_ids = variant_product_search(product_keyword, @seller, brand_id).pluck(:id)
-
end
-
-
7
if brand_keywords.present?
-
2
brand_ids = brand_ids_by_brand_name_keyword(brand_keywords)
-
2
catalogues_scope = catalogues_scope.where(brand_id: brand_ids)
-
end
-
-
7
if brand_id.present?
-
2
catalogues_scope = catalogues_scope.where(brand_id: brand_id)
-
end
-
-
7
if warehouse_id.present?
-
1
warehouse_catalogue_ids = WarehouseCatalogue.where.not(warehouse_id: warehouse_id).pluck(:catalogue_id)
-
end
-
-
7
catalogue_ids = (catalogues_scope.pluck(:id) + variant_product_ids) - warehouse_catalogue_ids
-
7
unique_catalogue_ids = catalogue_ids.uniq
-
-
7
@catalogues = Catalogue.where(id: unique_catalogue_ids)
-
7
total_count = unique_catalogue_ids.size
-
-
7
if total_count > 0
-
6
@catalogues = paginate_catalogues(@catalogues, page_number, per_page)
-
6
render json: CatalogueSerializer.new(@catalogues).serializable_hash.merge(total_count: total_count), status: :ok
-
else
-
1
render_no_product_found
-
end
-
end
-
-
# // for seller existing products list in product create flow
-
1
def search_catalogues_by_brand
-
2
per_page = params[:per_page].presence&.to_i || 10
-
2
page_no = params[:page].presence&.to_i || 1
-
2
brand_id = params[:brand_id]
-
2
micro_category_id = params[:micro_category_id]
-
2
total_count = 0
-
-
2
catalogues = Catalogue.includes(:product_content).where(brand_id: brand_id, micro_category_id: micro_category_id).order(created_at: :desc)
-
-
2
if params[:product_keyword].present?
-
1
product_keyword = params[:product_keyword].strip.downcase
-
-
1
catalogues = catalogues.where("LOWER(product_contents.product_title) LIKE :query",query: "%#{product_keyword}%").references(:product_contents)
-
end
-
-
2
if catalogues.present?
-
2
total_count = catalogues.count
-
2
catalogues = paginate_catalogues(catalogues, page_no, per_page)
-
end
-
-
2
render json: CatalogueSerializer.new(catalogues).serializable_hash.merge(total_count: total_count), status: :ok
-
end
-
-
# // catalogues by category or deal
-
1
def list_catalogue_by_category
-
14
category = BxBlockCategories::Category.find_by(id: params[:category_id])
-
14
deal = Deal.active_deals.find_by(id: params[:deal_id])
-
14
brand = Brand.find_by(id: params[:brand_id], approve: true)
-
-
14
return render_no_product_found unless category.present? || deal.present? || brand.present?
-
-
13
if deal.present?
-
1
catalogues_ids = catalogues_by_active_deals(params[:deal_id])
-
1
catalogues = Catalogue.joins(:product_content).where(id: catalogues_ids, status: true)
-
12
elsif brand.present?
-
1
catalogues = Catalogue.joins(:product_content).where(brand_id: params[:brand_id], status: true)
-
else
-
11
catalogues = Catalogue.joins(:product_content).where(category_id: params[:category_id], status: true)
-
end
-
-
13
if params[:out_of_stocks]&.to_s == 'true'
-
1
catalogues = catalogues.where('COALESCE(stocks, 0) <= ?', 0)
-
12
elsif params[:out_of_stocks]&.to_s == 'false'
-
1
catalogues = catalogues.where('COALESCE(stocks, 0) > ?', 0)
-
end
-
-
13
min_range, max_range = get_min_max_value(catalogues)
-
-
13
apply_category_filters(catalogues)
-
-
13
if params[:custom_field_values].present?
-
1
catalogues = filter_by_custom_field_values(catalogues, params[:custom_field_values])
-
end
-
-
13
if params[:filter_by_rating].present?
-
2
catalogues = filter_by_ratings(catalogues,params[:filter_by_rating])
-
end
-
-
13
if params[:min_price].present? && params[:max_price].present?
-
2
catalogues = apply_price_filters(catalogues, params[:min_price], params[:max_price])
-
end
-
-
13
if params[:color_filter].present?
-
1
catalogues = filter_by_colors(catalogues, params[:color_filter])
-
end
-
-
13
per_page = params[:per_page].presence || 50
-
13
page = params[:page].presence || 1
-
-
13
if params[:sort_by].present?
-
3
catalogues = sort_catalogues(catalogues, params[:sort_by])
-
end
-
-
13
total_count = catalogues.count
-
-
13
catalogues = paginate_catalogues(catalogues, page, per_page)
-
-
13
render_search_results(catalogues, min_range, max_range, category&.name, total_count)
-
end
-
-
# // store menu product list
-
1
def list_store_menu_products
-
2
per_page = params[:per_page].presence&.to_i || 10
-
2
page_number = params[:page].presence&.to_i || 1
-
2
total_count = 0
-
2
@menu = BxBlockStoreManagement::StoreMenu.find_by(id: params[:menu_id])
-
2
if @menu.present?
-
1
store_m_products = @menu.catalogues
-
1
if store_m_products.present?
-
1
total_count = store_m_products.count
-
1
store_m_products = paginate_catalogues(store_m_products, page_number, per_page)
-
end
-
1
render json: CatalogueSerializer.new(store_m_products).serializable_hash.merge(total_count: total_count), status: :ok
-
else
-
1
render json: { error: "Menu not found" }, status: :unprocessable_entity
-
end
-
end
-
-
1
def sku_validate
-
3
sku = params[:sku]
-
-
3
unless sku
-
1
return render json: {
-
message: "SKU parameter is missing"
-
}, status: :bad_request
-
end
-
-
2
catalogue = Catalogue.left_joins(:product_variant_groups).where('LOWER(sku) LIKE :query OR LOWER(product_variant_groups.product_sku) LIKE :query', query: sku&.downcase).first
-
-
2
if catalogue
-
1
return render json: {
-
message: "Already exist in database"
-
}, status: :conflict
-
end
-
-
1
render json: {
-
message: "SKU is valid"
-
}, status: :ok
-
end
-
-
1
def update
-
2
return if @catalogue.nil?
-
-
2
if @catalogue.update(catalogue_params.merge(seller: @seller))
-
1
product_activity_log(@seller, "Product Updated!", "Product #{@catalogue.sku} was updated by #{@seller&.full_name}")
-
1
render json: CatalogueSerializer.new(@catalogue)
-
.serializable_hash,
-
status: :ok
-
else
-
1
render json: { errors: format_activerecord_errors(@catalogue.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def template_download
-
-
1
category = BxBlockCategories::Category.find_by(id: params[:category_id])
-
1
subcategory = BxBlockCategories::SubCategory.find_by(id: params[:subcategory_id])
-
1
minicategory = BxBlockCategories::MiniCategory.find_by(id: params[:minicategory_id])
-
1
microcategory = BxBlockCategories::MicroCategory.find_by(id: params[:microcategory_id])
-
1
brand = BxBlockCatalogue::Brand.find_by(id: params[:brand_id])
-
1
ship_unit = ['Centimeter','Meter','Inch','Feet']
-
-
columns_and_values = {
-
1
'Category': category&.name,
-
'SubCategory': subcategory&.name,
-
'MiniCategory': minicategory&.name,
-
'Micro Category': microcategory&.name,
-
'Brand Name': brand&.brand_name,
-
'Seller SKU': nil,
-
'Product Title': nil,
-
'Product Image': nil,
-
'GTIN': nil,
-
'MRP': nil,
-
'Retail Price': nil,
-
'Long Description': nil,
-
'Whats in the Package': nil,
-
251
'Country of Origin': CS.countries.map { |c| c[1] },
-
'Product Color': ["Purple", "Light Coral","Lime Green", "Yellow", "Grey", "Ocean Green", "Pink", "Sky blue"],
-
'Warranty Days': nil,
-
'Warranty Months': nil,
-
'Feature Bullet 1': nil,
-
'Feature Bullet 2': nil,
-
'Feature Bullet 3': nil,
-
'Feature Bullet 4': nil,
-
'Size': nil,
-
'Size Unit': ['Grams','KiloGrams','Centimeter','Millimeter'],
-
'Capacity': nil,
-
'Capacity Unit': ['Litre','Millilitre'],
-
'HS Code': nil,
-
'Prod Model Name': nil,
-
'Prod Model Number': nil,
-
'Number of Pieces': nil,
-
'Shipping Length': nil,
-
'Shipping Length Unit': ship_unit,
-
'Shipping Height': nil,
-
'Shipping Height Unit': ship_unit,
-
'Shipping Width': nil,
-
'Shipping Width Unit': ship_unit,
-
'Shipping Weight': nil,
-
'Shipping Weight Unit': ['Kilogram','Gram','Ounce (OZ)','pound (lb)'],
-
'Image URL 1': nil,
-
'Image URL 2': nil,
-
'Image URL 3': nil,
-
'Image URL 4': nil,
-
'Image URL 5': nil,
-
'Image URL 6': nil,
-
}
-
-
1
fieldables = [category,subcategory,minicategory,microcategory].compact
-
1
custom_fields = BxBlockCategories::CustomField.where(fieldable: fieldables).order(created_at: :asc)
-
1
custom_fields.each do |custom_field|
-
1
columns_and_values[custom_field.field_name.to_sym] = custom_field.custom_fields_options.map(&:option_name)
-
end
-
-
response_data = {
-
1
'headers': columns_and_values.keys.map(&:to_s),
-
'values': columns_and_values
-
}
-
-
1
render json: response_data
-
end
-
-
1
def bulk_upload
-
5
uploaded_file = params[:file]
-
5
return render_invalid_file_format_error unless valid_csv_file?(uploaded_file)
-
-
begin
-
4
spreadsheet = Roo::Spreadsheet.open(uploaded_file.path)
-
4
sheet = spreadsheet.sheet(0)
-
-
4
if sheet.last_row.nil?
-
1
return render json: { error: 'The uploaded file does not contain any data.' }, status: :unprocessable_entity
-
end
-
-
3
csv_data = sheet.parse(headers: true)
-
-
3
if csv_data.empty? || csv_data.all?(&:empty?)
-
return render json: { error: 'Please upload a file with proper data' }, status: :unprocessable_entity
-
end
-
rescue => e
-
return render json: { error: "The uploaded file contains an invalid format. Error: #{e.message} Please check the file and try again." }, status: :unprocessable_entity
-
end
-
-
3
skipped_rows = []
-
3
validation_errors = []
-
3
successful_rows = []
-
-
3
csv_data.each_with_index do |row, row_number|
-
16
next if row_number == 0
-
-
13
category_name = row['Category']
-
13
subcategory_name = row['SubCategory']
-
13
minicategory_name = row['MiniCategory']
-
13
microcategory_name = row[MICRO_CATEGORY_COLUMN]
-
13
brand_name = row[BRAND_NAME_COLUMN]
-
-
13
brand = find_brand(brand_name)
-
-
13
if brand && check_brand_for_restriction(brand)
-
1
error_message = "Row #{row_number}: The brand '#{brand_name}' you have selected has some restrictions for sellers or distributors,if you have products of the brand, please submit a permit to sell under this brand, and submit a request for approval."
-
1
skipped_rows << error_message
-
1
validation_errors << error_message
-
1
next
-
end
-
-
12
category = find_category(category_name)
-
12
subcategory = find_subcategory(subcategory_name)
-
12
minicategory = find_minicategory(minicategory_name)
-
12
microcategory = find_microcategory(microcategory_name)
-
-
12
missing_categories = []
-
-
12
{ 'Category' => category, 'Subcategory' => subcategory, 'Minicategory' => minicategory, 'Microcategory' => microcategory, 'Brand' => brand }.each do |name, value|
-
60
missing_categories << name if value.nil?
-
end
-
-
12
if missing_categories.any?
-
4
error_message = "Row #{row_number}: #{missing_categories.join(', ')} not found or created."
-
4
skipped_rows << error_message
-
4
validation_errors << error_message
-
4
next
-
end
-
-
8
create_catalogue(row, row_number, skipped_rows, validation_errors, successful_rows)
-
-
end
-
-
3
render_upload_result(skipped_rows, validation_errors, successful_rows)
-
end
-
-
1
private
-
-
1
def load_catalogue
-
6
@catalogue = Catalogue.find_by(id: params[:id])
-
-
6
if @catalogue.nil?
-
2
render json: {
-
message: "Catalogue with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def find_seller
-
26
@seller = AccountBlock::Account.find_by(id: @token.id, user_type: 'seller')
-
26
render json: {errors: 'Seller is invalid'} and return unless @seller
-
end
-
-
1
def catalogue_params
-
4
params.permit(:sku, :besku, :bibc, :product_image, :status, :category_id, :brand_id, :warehouse_id, :product_title, :sub_category_id, :mini_category_id, :micro_category_id, :parent_catalogue_id, :fulfilled_type, :product_type, :content_status, :seller_id)
-
end
-
-
1
def valid_csv_file?(file)
-
5
%w[application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-excel application/x-excel text/csv application/csv].include?(file.content_type) if file
-
end
-
-
1
def create_catalogue(row, row_number, skipped_rows, validation_errors, successful_rows)
-
8
catalog_params = build_catalog_params(row)
-
8
catalogue = Catalogue.new(catalog_params)
-
8
custom_field_error = []
-
8
attach_image_to_catalogue(catalogue, row['Product Image'])
-
8
product_content_params = build_product_content_params(row)
-
8
product_content = catalogue.build_product_content(product_content_params)
-
-
8
if catalogue.valid? && product_content.valid?
-
4
ActiveRecord::Base.transaction do
-
4
catalogue.save!
-
4
product_content.save!
-
-
4
process_custom_fields(catalogue, row, row_number, skipped_rows, validation_errors, custom_field_error)
-
-
4
raise ActiveRecord::Rollback unless custom_field_error.blank?
-
3
successful_rows << "Row #{row_number}: Uploaded successfully"
-
end
-
else
-
4
catalogue_errors = catalogue.errors.full_messages_for(:sku).join(', ').present? && catalogue.errors.full_messages_for(:sku).join(', ') == "Sku has already been taken" ? "SKU / Product is already added" : catalogue.errors.full_messages_for(:sku).join(', ')
-
4
product_image_error = catalogue.errors.full_messages_for(:product_image).join(', ')
-
19
product_content_errors = product_content.errors.full_messages.reject { |error_message| error_message.include?("Unique psku can't be blank") }.join(', ')
-
-
4
combined_errors = [catalogue_errors, product_image_error, product_content_errors].reject(&:blank?).join(', ')
-
-
4
skipped_rows << row
-
4
validation_errors << "Row #{row_number}: Validation error(s): #{combined_errors}"
-
end
-
rescue StandardError => e
-
skipped_rows << row
-
validation_errors << "Row #{row_number}: Error(s): #{e.message}"
-
end
-
-
1
def process_custom_fields(catalogue, row, row_number, skipped_rows, validation_errors, custom_field_error)
-
4
fieldables = [catalogue.category, catalogue.sub_category, catalogue.mini_category, catalogue.micro_category].compact
-
4
custom_fields = BxBlockCategories::CustomField.where(fieldable: fieldables)
-
4
custom_fields.each do |custom_field|
-
5
if custom_field.mandatory? && row[custom_field.field_name].blank?
-
1
error_var = "Row #{row_number}: Mandatory field '#{custom_field.field_name}' is missing"
-
1
skipped_rows << row
-
1
custom_field_error << error_var
-
1
validation_errors << error_var
-
end
-
5
content = catalogue.catalogue_contents.find_by(custom_field_id: custom_field.id)
-
5
if content.present? && row[custom_field.field_name].present?
-
3
value = row[custom_field.field_name].strip
-
3
allowed_options = custom_field.custom_fields_options.pluck(:option_name)
-
-
3
if !value.in?(allowed_options)
-
error_var = "Row #{row_number}: Value '#{value}' for custom field '#{custom_field.field_name}' is not valid. Allowed values are: #{allowed_options.join(', ')}"
-
skipped_rows << row
-
custom_field_error << error_var
-
validation_errors << error_var
-
else
-
3
content.value = value
-
3
content.save!
-
end
-
end
-
end
-
end
-
-
1
def check_brand_for_restriction(brand)
-
13
brand.restricted && brand.account != @seller && brand.restricted_brands.where(seller_id: @seller.id, approved: true).empty?
-
end
-
-
1
def build_catalog_params(row)
-
{
-
8
category: find_category(row['Category']),
-
sub_category: find_subcategory(row['SubCategory']),
-
mini_category: find_minicategory(row['MiniCategory']),
-
micro_category: find_microcategory(row[MICRO_CATEGORY_COLUMN]),
-
brand: find_brand(row[BRAND_NAME_COLUMN]),
-
sku: row['Seller SKU']&.strip,
-
seller: @seller,
-
product_title: row['Product Title']&.strip
-
}
-
end
-
-
1
def attach_image_to_catalogue(catalogue, image_url)
-
8
return if image_url.blank?
-
-
begin
-
6
image_file = URI.open(image_url)
-
6
catalogue.product_image.attach(io: image_file, filename: File.basename(image_url))
-
rescue OpenURI::HTTPError, SocketError => e
-
catalogue.errors.add(:product_image, "could not be attached: #{e.message}")
-
end
-
end
-
-
1
def build_product_content_params(row)
-
size_and_capacity_params = {
-
8
size: row['Size'],
-
size_unit: row['Size Unit'],
-
capacity: row['Capacity'],
-
capacity_unit: row['Capacity Unit'],
-
8
hs_code: row['HS Code'].present? ? row['HS Code'].to_i.to_s : nil,
-
prod_model_name: row['Prod Model Name'],
-
prod_model_number: row['Prod Model Number'],
-
number_of_pieces: row['Number of Pieces']
-
}
-
-
shipping_detail_params = {
-
8
shipping_length: row['Shipping Length'],
-
shipping_length_unit: row['Shipping Length Unit'],
-
shipping_height: row['Shipping Height'],
-
shipping_height_unit: row['Shipping Height Unit'],
-
shipping_width: row['Shipping Width'],
-
shipping_width_unit: row['Shipping Width Unit'],
-
shipping_weight: row['Shipping Weight'],
-
shipping_weight_unit: row['Shipping Weight Unit']
-
}
-
-
params_hash = {
-
8
gtin: row['GTIN']&.to_i&.to_s,
-
unique_psku: row['Seller SKU']&.strip,
-
brand_name: row['Brand Name']&.strip,
-
product_title: row['Product Title']&.strip,
-
mrp: row['MRP'],
-
retail_price: row['Retail Price'],
-
warranty_days: row['Warranty Days'],
-
warranty_months: row['Warranty Months'],
-
long_description: row['Long Description'],
-
whats_in_the_package: row['Whats in the Package'],
-
country_of_origin: row['Country of Origin'],
-
product_color: row['Product Color'],
-
image_urls: build_image_urls_params(row),
-
feature_bullets: build_feature_bullets_params(row)
-
}
-
-
8
params_hash[:size_and_capacity] = BxBlockCatalogue::SizeAndCapacity.new(size_and_capacity_params) if size_and_capacity_params.values.any?(&:present?)
-
8
params_hash[:shipping_detail] = BxBlockCatalogue::ShippingDetail.new(shipping_detail_params) if shipping_detail_params.values.any?(&:present?)
-
-
8
params_hash
-
end
-
-
1
def build_feature_bullets_params(row)
-
8
feature_bullets = []
-
-
8
(1..5).each do |bullet_number|
-
40
bullet_key = "Feature Bullet #{bullet_number}"
-
40
bullet_value = row[bullet_key]
-
-
40
if bullet_value.present?
-
14
feature_bullets << BxBlockCatalogue::FeatureBullet.new(
-
field_name: bullet_key,
-
value: bullet_value
-
)
-
end
-
end
-
-
8
feature_bullets
-
end
-
-
1
def build_image_urls_params(row)
-
8
image_urls = []
-
-
8
(1..6).each do |image_no|
-
48
image_key = "Image URL #{image_no}"
-
48
image_value = row[image_key]
-
-
48
if image_value.present?
-
9
image_urls << BxBlockCatalogue::ImageUrl.new(
-
url: image_value
-
)
-
end
-
end
-
-
8
image_urls
-
end
-
-
1
def render_upload_result(skipped_rows, validation_errors, successful_rows)
-
3
bulk_upload_logs(skipped_rows, validation_errors, successful_rows)
-
3
if skipped_rows.empty?
-
1
render json: { message: 'Bulk upload completed successfully', successful_rows: successful_rows }, status: :ok
-
else
-
2
render json: { message: 'Bulk upload completed with errors', skipped_rows: skipped_rows, successful_rows: successful_rows, validation_errors: validation_errors }, status: :unprocessable_entity
-
end
-
end
-
-
1
def bulk_upload_logs(skipped_rows, validation_errors, successful_rows)
-
details = "Message: 'Bulk upload completed'\n" \
-
3
"Successful Rows: #{successful_rows}\n" \
-
"Skipped Rows: #{skipped_rows}\n" \
-
"Validation Errors: #{validation_errors}"
-
-
3
product_activity_log(@seller, "Bulk Products Uploaded", details)
-
end
-
-
1
def render_invalid_file_format_error
-
1
render json: { error: 'Invalid file format' }, status: :unprocessable_entity
-
end
-
-
1
def check_favourite_for_buyer(catalogue, params)
-
2
user = AccountBlock::Account.buyer_accounts.find_by(id: params[:account_id])
-
-
2
if user.present?
-
favourite = user.favourites.find_by(favouriteable_id: catalogue&.id, product_variant_group_id: params[:product_variant_group_id].presence)
-
-
if favourite.present?
-
return {
-
id: favourite.id,
-
favouriteable_id: favourite.favouriteable_id,
-
favouriteable_type: favourite.favouriteable_type,
-
user_id: favourite.user_id,
-
product_variant_group_id: favourite.product_variant_group_id,
-
wishlist: true
-
}
-
end
-
end
-
-
2
{ wishlist: false }
-
end
-
-
1
def product_activity_log(user, message, details)
-
5
BxBlockActivitylog::ActivityLog.create(
-
user: @seller,
-
action: message,
-
details: details,
-
accessed_at: Time.current
-
)
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class DealCataloguesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :set_deal
-
1
before_action :set_deal_catalogue, only: [:show, :update, :destroy]
-
1
before_action :validate_json_web_token, only: [:show, :index, :create, :update, :destroy]
-
1
before_action :get_seller, only: [:index, :create, :update, :destroy]
-
-
-
1
def index
-
1
per_page = params[:per_page].presence&.to_i || 10
-
1
page_number = params[:page].presence&.to_i || 1
-
1
@deal_catalogues = @deal.deal_catalogues.all.where(seller_id: @seller.id).where.not(status: 'expired').order(created_at: :desc)
-
1
total_count = @deal_catalogues.count
-
-
1
if @deal_catalogues.present?
-
1
@deal_catalogues = paginate_catalogues(@deal_catalogues, page_number, per_page)
-
end
-
-
1
render json: DealCatalogueSerializer.new(@deal_catalogues).serializable_hash.merge(total_count: total_count), status: :ok
-
end
-
-
1
def show
-
1
render json: DealCatalogueSerializer.new(@deal_catalogue).serializable_hash
-
end
-
-
1
def create
-
4
seller_deals_params = params.permit(seller_deals: [:catalogue_id,:deal_price,:seller_id]).require(:seller_deals)
-
-
# if @deal.discount_type == 'flat'
-
# seller_deals_params = seller_deals_params.map { |param| param.merge(deal_price: @deal.discount_value)}
-
# end
-
-
begin
-
4
@deal.deal_catalogues.transaction do
-
4
@deal_catalogues = @deal.deal_catalogues.create!(seller_deals_params)
-
end
-
2
render json: DealCatalogueSerializer.new(@deal_catalogues).serializable_hash, status: :created
-
2
rescue ActiveRecord::RecordInvalid => exception
-
2
render json: { error: exception.message }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
3
if @deal_catalogue.update(jsonapi_deserialize(params))
-
2
render json: DealCatalogueSerializer.new(@deal_catalogue).serializable_hash, status: :ok
-
else
-
1
render json: { errors: format_activerecord_errors(@deal_catalogue.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @deal_catalogue.destroy
-
1
render json: {
-
message: "Deal Catalogue has been removed"
-
}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def get_seller
-
9
@seller = AccountBlock::Account.find_by(id: @token.id,user_type: 'seller')
-
9
render json: {message: "Seller invalid"} and return unless @seller.present?
-
end
-
-
1
def set_deal
-
11
@deal = Deal.find_by(id: params[:deal_id])
-
11
if @deal.nil?
-
render json: {
-
message: "Deal not available"
-
}, status: :not_found
-
end
-
end
-
-
1
def set_deal_catalogue
-
6
@deal_catalogue = @deal.deal_catalogues.find_by(id: params[:id])
-
6
if @deal_catalogue.nil?
-
1
render json: {
-
message: "Deal Catalogue not found"
-
}, status: :not_found
-
end
-
end
-
-
1
def deal_catalogue_params
-
params.require(:data).require(:attributes).permit(:catalogue_id, :deal_price, :seller_id, :status)
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class DealsController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :find_deal, only: [:show, :catalogues_by_deals]
-
-
1
def index
-
1
per_page = params[:per_page].presence&.to_i || 10
-
1
page_number = params[:page].presence&.to_i || 1
-
1
@deals = Deal.all.active_deals.order(created_at: :desc)
-
1
total_count = @deals.count
-
-
1
if @deals.present?
-
1
@deals = paginate_catalogues(@deals, page_number, per_page)
-
end
-
-
1
render json: DealSerializer.new(@deals).serializable_hash.merge(total_count: total_count), status: :ok
-
end
-
-
1
def show
-
1
render json: DealSerializer.new(@deal).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def find_deal
-
2
@deal = Deal.all.active_deals.find_by(id: params[:id])
-
2
if @deal.nil?
-
1
render json: {
-
message: "Deal not available"
-
}, status: :not_found
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class GatedBrandsController < ApplicationController
-
1
before_action :set_gated_brand, only: [:show, :update, :destroy]
-
1
before_action :validate_json_web_token, only: [:create]
-
-
1
def index
-
1
@gated_brands = GatedBrand.all
-
1
render json: GatedBrandSerializer.new(@gated_brands).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: GatedBrandSerializer.new(@gated_brand).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@gated_brand = GatedBrand.new(gated_brand_params)
-
-
2
if @gated_brand.save
-
1
render json: GatedBrandSerializer.new(@gated_brand).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(@gated_brand.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
# def update
-
# if @gated_brand.update(gated_brand_params)
-
# render json: @gated_brand
-
# else
-
# render json: @gated_brand.errors, status: :unprocessable_entity
-
# end
-
# end
-
-
# def destroy
-
# @gated_brand.destroy
-
# head :no_content
-
# end
-
-
1
private
-
-
1
def set_gated_brand
-
1
@gated_brand = GatedBrand.find(params[:id])
-
end
-
-
1
def gated_brand_params
-
2
params.permit(:brand_id, :approved, :reseller_permit_document)
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class HelpfulReviewsController < ApplicationController
-
1
before_action :validate_json_web_token
-
1
before_action :find_user
-
1
before_action :find_review, only: [:create, :destroy]
-
-
1
def create
-
3
helpful_review = @review.helpful_reviews.new(customer: @account)
-
-
3
if helpful_review.save
-
2
render json: { message: 'Marked as helpful', helpful_count: @review.helpful_count }, status: :ok
-
else
-
1
render json: { error: 'Could not mark as helpful' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
3
helpful_review = @review.helpful_reviews.find_by(customer: @account)
-
-
3
if helpful_review&.destroy
-
2
render json: { message: 'Unmarked as helpful', helpful_count: @review.helpful_count }, status: :ok
-
else
-
1
render json: { error: 'Could not unmark as helpful' }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def find_review
-
6
@review = BxBlockCatalogue::Review.find(params[:review_id])
-
end
-
-
1
def find_user
-
7
@account = AccountBlock::Account.find_by(id: @token.id, user_type: 'buyer')
-
7
if @account.nil?
-
1
return render json: { message: 'Account does not exist' },
-
status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ParentCataloguesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
-
1
before_action :validate_json_web_token, only: [:search_parent_catalogues_by_title_or_brand_name]
-
-
1
def search_parent_catalogues_by_title_or_brand_name
-
3
per_page = params[:per_page].presence&.to_i || 10
-
3
page_number = params[:page].presence&.to_i || 1
-
3
parent_product_keyword = params[:product_keyword].to_s.strip
-
3
brand_keywords = params[:brand_keyword]&.split(',')&.map(&:strip)
-
3
parent_catalogues = ParentCatalogue.all
-
3
total_count = parent_catalogues.count
-
-
3
if parent_product_keyword.present?
-
2
parent_catalogues = parent_catalogues.where('LOWER(product_title) LIKE ?', "%#{parent_product_keyword.downcase}%")
-
2
total_count = parent_catalogues.count
-
end
-
-
3
if brand_keywords.present?
-
2
brand_ids = brand_ids_by_brand_name_keyword(brand_keywords)
-
2
parent_catalogues = parent_catalogues.where(brand_id: brand_ids)
-
2
total_count = parent_catalogues.count
-
end
-
-
3
@parent_catalogues = parent_catalogues.page(page_number).per(per_page)
-
-
3
if @parent_catalogues.present?
-
2
render json: ParentCatalogueSerializer.new(@parent_catalogues).serializable_hash.merge(total_count: total_count), status: :ok
-
else
-
1
render_no_product_found
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ProductContentsController < ApplicationController
-
1
before_action :set_catalogue
-
1
before_action :validate_json_web_token, only: [:create, :update]
-
-
1
def index
-
1
@product_content = @catalogue.product_content
-
1
render json: ProductContentSerializer.new(@product_content).serializable_hash, status: :ok
-
end
-
-
# def show
-
# @product_content = @catalogue.product_content
-
# render json: @product_content
-
# end
-
-
1
def create
-
3
@product_content = @catalogue.product_content
-
-
3
@product_content ||= ProductContent.new(catalogue: @catalogue)
-
3
@product_content.assign_attributes(product_content_params.except(:catalogue_content_attributes))
-
-
3
if @product_content.save
-
2
update_catalogue_content
-
2
render json: ProductContentSerializer.new(@product_content).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(@product_content.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
3
@product_content = ProductContent.find(params[:id])
-
-
3
if @product_content.update(product_content_params.except(:catalogue_content_attributes))
-
2
update_catalogue_content
-
2
render json: ProductContentSerializer.new(@product_content).serializable_hash, status: :ok
-
else
-
1
render json: { errors: format_activerecord_errors(@product_content.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def set_catalogue
-
7
@catalogue = Catalogue.find(params[:catalogue_id])
-
end
-
-
1
def product_content_params
-
10
params.require(:data)
-
.require(:attributes)
-
.permit(:gtin, :unique_psku, :brand_name, :product_title, :mrp, :retail_price, :long_description, :whats_in_the_package, :country_of_origin,:product_color, :warranty_days,:warranty_months, :dispenser_type, :scent_type, :target_use, :style_name,
-
size_and_capacity_attributes: [:id, :size, :size_unit, :hs_code, :prod_model_name, :capacity, :capacity_unit, :prod_model_number, :number_of_pieces],
-
shipping_detail_attributes: [:id, :shipping_length, :shipping_length_unit, :shipping_height, :shipping_height_unit, :shipping_width, :shipping_width_unit, :shipping_weight, :shipping_weight_unit],
-
image_urls_attributes: [:id, :url, :_destroy],
-
feature_bullets_attributes: [:id, :field_name, :value, :_destroy],
-
special_features_attributes: [:id, :field_name, :value],
-
catalogue_content_attributes: [:id, :custom_field_name, :value])
-
end
-
-
# as this is working tested with extra method but without this its working so commenting
-
-
# def update_associated_content
-
# @product_content.image_urls.each do |image_url|
-
# image_url.destroy if image_url._destroy == true
-
# end
-
-
# @product_content.feature_bullets.each do |feature_bullet|
-
# feature_bullet.destroy if feature_bullet._destroy == true
-
# end
-
-
# end
-
-
1
def update_catalogue_content
-
4
catalogue_content_attributes = product_content_params.delete(:catalogue_content_attributes)
-
4
return if catalogue_content_attributes.blank?
-
-
2
catalogue_content_attributes.each do |attr|
-
2
catalogue_content_id = attr[:id]
-
2
value = attr[:value]
-
-
2
catalogue_content = @catalogue.catalogue_contents.find_by(id: catalogue_content_id)
-
2
next if catalogue_content.blank?
-
2
catalogue_content.update(value: value, custom_field_name: catalogue_content&.custom_field&.field_name)
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ProductVariantGroupsController < ApplicationController
-
-
1
before_action :set_catalogue
-
1
before_action :set_product_variant_group, only: [:show, :update, :destroy]
-
1
before_action :validate_json_web_token, only: [:create, :update, :destroy]
-
-
1
def create
-
2
ActiveRecord::Base.transaction do
-
2
product_variant_groups = []
-
-
2
params['_json'].each do |variant_group_params|
-
3
product_variant_group = @catalogue.product_variant_groups.new(
-
product_sku: variant_group_params["product_sku"],
-
catalogue_variant_id: variant_group_params["catalogue_variant_id"]
-
)
-
-
3
variant_group_params["group_attributes_attributes"].each do |group_attribute_params|
-
5
product_variant_group.group_attributes.build(group_attribute_params.permit("attribute_option_id","variant_attribute_id","attribute_name", "option"))
-
end
-
-
3
if product_variant_group.save
-
2
product_variant_groups << product_variant_group
-
2
product_variant_group.create_and_associate_variant_product
-
else
-
2
render json: { errors: product_variant_group.errors.full_messages.map {|message| message.gsub("Product ","")} }, status: :unprocessable_entity
-
1
raise ActiveRecord::Rollback
-
end
-
end
-
-
1
render json: BxBlockCatalogue::ProductVariantGroupSerializer.new(product_variant_groups).serializable_hash, status: :created
-
end
-
end
-
-
1
def index
-
1
render json: BxBlockCatalogue::ProductVariantGroupSerializer.new(@catalogue.product_variant_groups).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: BxBlockCatalogue::ProductVariantGroupSerializer.new(@product_variant_group).serializable_hash, status: :ok
-
end
-
-
1
def update
-
2
if @product_variant_group.update(product_variant_groups_params)
-
1
render json: BxBlockCatalogue::ProductVariantGroupSerializer.new(@product_variant_group).serializable_hash, status: :ok
-
else
-
1
render json: { errors: format_activerecord_errors(@product_variant_group.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
-
1
if @product_variant_group.destroy
-
1
render json: {message: "Product variant Destroyed"}, status: :ok
-
end
-
-
end
-
-
1
private
-
-
1
def set_catalogue
-
7
@catalogue = Catalogue.find(params[:catalogue_id])
-
end
-
-
1
def set_product_variant_group
-
4
@product_variant_group = BxBlockCatalogue::ProductVariantGroup.find(params[:id])
-
end
-
-
1
def product_variant_groups_params
-
2
params.permit(:catalogue_variant_id, :product_sku, :product_description, :price, :product_title,
-
product_images: [],
-
group_attributes_attributes: [
-
:id,
-
:variant_attribute_id,
-
:attribute_option_id,
-
:attribute_name,
-
:option,
-
:_destroy
-
]
-
)
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class RestrictedBrandsController < ApplicationController
-
1
before_action :validate_json_web_token
-
1
before_action :set_seller
-
1
before_action :set_restricted_brand, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@restricted_brands = @seller.restricted_brands.all
-
1
render json: RestrictedBrandSerializer.new(@restricted_brands).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: RestrictedBrandSerializer.new(@restricted_brand).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@restricted_brand = RestrictedBrand.new(restricted_brand_params.merge(seller: @seller))
-
-
2
if @restricted_brand.save
-
1
render json: RestrictedBrandSerializer.new(@restricted_brand).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(@restricted_brand.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @restricted_brand.update(restricted_brand_params)
-
1
render json: @restricted_brand, status: :ok
-
else
-
1
render json: @restricted_brand.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
@restricted_brand.destroy
-
1
head :no_content
-
end
-
-
1
private
-
-
1
def set_restricted_brand
-
4
@restricted_brand = RestrictedBrand.find(params[:id])
-
end
-
-
1
def set_seller
-
7
@seller = AccountBlock::Account.find_by(id: @token.id,user_type: 'seller')
-
7
render json: {message: "Seller invalid"} and return unless @seller.present?
-
end
-
-
1
def restricted_brand_params
-
4
params.permit(:brand_id, :approved, :reseller_permit_document, :seller_id)
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ReviewsController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
-
1
before_action :validate_json_web_token, except: [:customer_rating_and_reviews]
-
1
before_action :check_review, only: [:show, :destroy]
-
1
before_action :check_catalogue, only: [:index, :customer_rating_and_reviews]
-
1
before_action :check_user, only: [:create, :update]
-
1
before_action :check_valid_params, only: [:user_review_listing]
-
1
before_action :get_seller, only: [:user_review_listing, :seller_happiness_indicator]
-
-
#create review for product, seller, adn delivery
-
1
def create
-
2
create_review(:product) if params[:product].present?
-
2
create_review(:seller) if params[:seller].present?
-
2
create_review(:delivery) if params[:delivery].present?
-
end
-
-
1
def update
-
50
update_review_params = extract_review_params(:review).reject! { |_, value| value.nil? }
-
-
5
@review = Review.find_by(id: params[:id])
-
5
render json: { errors: "Review not found" }, status: :not_found and return if @review.nil?
-
-
4
HelpfulReview.create(review_id: params[:id], customer: @account) if update_review_params[:helpful]
-
-
4
if @review.update(update_review_params.except(:helpful))
-
2
render json: ReviewSerializer.new(@review, params: { current_account: @account }).serializable_hash, status: :ok
-
else
-
2
render json: { errors: format_activerecord_errors(@review.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def customer_rating_and_reviews
-
3
per_page = params[:per_page].presence || 10
-
3
page = params[:page].presence || 1
-
-
3
if params[:review_type].present?
-
1
reviews = @catalogue.review_and_ratings.approved_reviews.where(review_type: params[:review_type]).order(created_at: :desc)
-
else
-
2
reviews = @catalogue.review_and_ratings.approved_reviews.order(created_at: :desc)
-
end
-
3
customer_ratings = seller_rating_percentage(reviews)
-
3
average_rating = average_rating(reviews).round(1)
-
3
total_rating = total_rating(reviews)
-
3
total_reviews = reviews.count
-
-
3
reviews = reviews.where("title IS NOT NULL AND title != '' OR description IS NOT NULL AND description != ''")
-
-
3
if reviews.present?
-
3
reviews = paginate_catalogues(reviews, page, per_page)
-
end
-
-
3
account = AccountBlock::Account.find_by(id: params[:account_id])
-
-
3
serializer = ReviewSerializer.new(reviews, params: { current_account: account }).serializable_hash
-
-
3
render json: { customer_ratings: customer_ratings, average_rating: average_rating, total_rating: total_rating, reviews: serializer, total_reviews: total_reviews }, status: :ok
-
end
-
-
1
def show
-
1
render json: ReviewSerializer.new(@review, serialization_options).serializable_hash, status: :ok
-
end
-
-
1
def index
-
1
serializer = ReviewSerializer.new(@catalogue.review_and_ratings.approved_reviews, serialization_options)
-
-
1
render json: serializer, status: :ok
-
end
-
-
1
def user_review_listing
-
1
serializer = ReviewSerializer.new(@seller.review_and_ratings.approved_reviews, serialization_options)
-
1
render json: serializer, status: :ok
-
end
-
-
1
def buyer_review_listing
-
1
buyer = AccountBlock::Account.find_by(id: @token.id, user_type: 'buyer')
-
1
render json: {error: "buyer not found"}, status: :unprocessable_entity and return unless buyer
-
-
1
find_reviews = Review.where(order_item_id: params[:order_item_id], reviewer_id: buyer.id)
-
-
1
render json: ReviewSerializer.new(find_reviews), status: :ok
-
end
-
-
1
def seller_happiness_indicator
-
3
seller_review_collection = @seller.review_and_ratings.order(created_at: :desc).group_by(&:review_type)
-
-
3
if seller_review_collection.present?
-
2
response = {}
-
2
reviews_filtered = []
-
-
2
seller_review_collection.each do |type, reviews|
-
3
next unless reviews.present?
-
-
3
average_rating = average_rating(reviews).round(1)
-
3
review_percentages = seller_rating_percentage(reviews)
-
-
3
reviews_to_display = if params[:filter_by].present?
-
4
reviews_filtered = reviews.select { |review| params[:filter_by].map(&:to_i).include?(review.rating) }
-
2
add_reviewer_name(reviews_filtered)
-
else
-
1
add_reviewer_name(reviews)
-
end
-
-
3
response[type] = {
-
reviews: reviews_to_display,
-
meta: {
-
type: type,
-
average_rating: average_rating,
-
seller_review_percentages: review_percentages,
-
seller_total_rating: total_rating(reviews)
-
}
-
}
-
end
-
-
2
render json: response, status: :ok
-
else
-
1
render json: { message: "No reviews found for this seller" }, status: :not_found
-
end
-
end
-
-
1
def destroy
-
1
if @review.destroy
-
1
render json: {message: "Review destroyed successfully"}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def check_valid_params
-
2
valid_review_types = %w[seller delivery product]
-
2
unless valid_review_types.include?(params[:review_type])
-
1
return render json: { error: { message: 'Invalid review_type' } }, status: :unprocessable_entity
-
end
-
end
-
-
1
def check_user
-
7
@account = AccountBlock::Account.find_by(id: @token.id)
-
7
if @account.nil?
-
return render json: { message: 'Account does not exist' },
-
status: :not_found
-
end
-
end
-
-
1
def create_review(type)
-
2
review = BxBlockCatalogue::Review.new(extract_review_params(type).merge(reviewer_id: @account.id).except(:helpful))
-
2
if review.save
-
1
render json: {
-
review: ReviewSerializer.new(review).serializable_hash,
-
message: "Review added successfully"
-
}, status: :created
-
else
-
1
return render json: { errors: format_activerecord_errors(review.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def check_review
-
3
@review = Review.find_by(id: params[:id], is_approved: true)
-
3
unless @review.present?
-
1
render json: {
-
message: "Review with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def check_catalogue
-
5
@catalogue = Catalogue.find_by(id: params[:catalogue_id])
-
5
unless @catalogue.present?
-
1
render json: {
-
message: "Reviews not found with Catalogue id #{params[:catalogue_id]}"
-
}, status: :not_found
-
end
-
end
-
-
1
def get_seller
-
4
@seller = AccountBlock::Account.find_by(id: @token.id,user_type: 'seller')
-
4
unless @seller.present?
-
render json: {
-
message: "Seller not found"
-
}, status: :not_found
-
end
-
end
-
-
1
def serialization_options
-
3
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
-
1
def extract_review_params(type)
-
7
review_params = params[type] || ActionController::Parameters.new
-
review_attributes = {
-
7
rating: review_params[:rating],
-
title: review_params[:title],
-
description: review_params[:description],
-
catalogue_id: review_params[:catalogue_id],
-
review_type: review_params[:review_type],
-
review_images: review_params[:review_images],
-
account_id: review_params[:account_id],
-
order_item_id: review_params[:order_item_id],
-
helpful: review_params[:helpful]
-
}
-
7
review_attributes
-
end
-
-
1
def add_reviewer_name(reviews)
-
3
reviews.map do |review|
-
3
reviewer_name = AccountBlock::Account.find_by(id: review.reviewer_id)&.full_name
-
3
reviewer_images = review.review_images.map { |image| "#{ENV['BASE_URL']}#{Rails.application.routes.url_helpers.rails_blob_path(image, only_path: true)}" }
-
3
review.as_json.merge(reviewer_name: reviewer_name, review_images: reviewer_images)
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class StoreFrontsController < ApplicationController
-
1
before_action :validate_json_web_token
-
1
skip_before_action :validate_json_web_token, only: [:list_reviews, :average_rating_for_product, :ratings_percentage_for_product, :latest_review_for_product]
-
1
before_action :set_account, except: [:average_rating_for_product, :latest_review_for_product, :ratings_percentage_for_product, :list_reviews]
-
1
before_action :filter_by_category_and_ratings, only: [:index]
-
1
before_action :popular_catalog, only: [:popular_product]
-
1
before_action :find_product, only: [:average_rating_for_product, :ratings_percentage_for_product, :latest_review_for_product]
-
-
1
def index
-
2
render json: StoreFrontSerializer.new(@catalogues), status: :ok
-
end
-
-
1
def latest_product
-
1
latest_catalog = @account.catalogues.order(created_at: :desc)
-
1
render json: StoreFrontSerializer.new(latest_catalog), status: :ok
-
end
-
-
1
def popular_product
-
1
render json: StoreFrontSerializer.new(@popular_products), status: :ok
-
end
-
-
1
def average_rating_for_seller
-
1
average_rating = @account.review_and_ratings.average(:rating)
-
1
render json: {average_rating: average_rating}, status: :ok
-
end
-
-
1
def average_rating_for_product
-
2
average_rating = @product.review_and_ratings.average(:rating)
-
2
if average_rating.present?
-
1
render json: { average_rating: average_rating }, status: :ok
-
else
-
1
render json: { message: "No average rating found" }, status: :not_found
-
end
-
end
-
-
1
def ratings_percentage
-
1
ratings = @account.review_and_ratings
-
1
seller_total_rating = @account.review_and_ratings.pluck(:rating).sum
-
1
total_ratings = ratings.count
-
-
1
percentages = {}
-
1
(1..5).each do |rating|
-
5
rating_count = ratings.where(rating: rating).count
-
5
percentages[rating] = (rating_count.to_f / total_ratings.to_f) * 100
-
end
-
-
1
render json: {seller_review_percentages: percentages, seller_total_rating: seller_total_rating}, status: :ok
-
end
-
-
1
def ratings_percentage_for_product
-
2
ratings = @product.review_and_ratings
-
2
if ratings.present?
-
1
product_total_rating = ratings.sum(:rating)
-
1
total_ratings = ratings.count
-
1
percentages = {}
-
1
(1..5).each do |rating|
-
5
rating_count = ratings.where(rating: rating).count
-
5
percentages[rating] = (rating_count.to_f / total_ratings.to_f) * 100
-
end
-
1
render json: { product_review_percentages: percentages, product_total_rating: product_total_rating }, status: :ok
-
else
-
1
render json: { message: "Rating Not Found" }, status: :not_found
-
end
-
end
-
-
1
def latest_review_for_seller
-
1
ratings = @account.review_and_ratings.order(created_at: :desc).limit(2)
-
1
render json: StoreFrontListingSerializer.new(ratings), status: :ok
-
end
-
-
1
def latest_review_for_product
-
2
latest_reviews = @product.review_and_ratings.order(created_at: :desc)
-
2
if latest_reviews.present?
-
1
render json: ReviewSerializer.new(latest_reviews), status: :ok
-
else
-
1
render json: { message: 'Latest Ratings not Found' }, status: :not_found
-
end
-
end
-
-
1
def list_reviews
-
4
review_collection = BxBlockCatalogue::Review.where(catalogue_id: params[:catalogue_id]).group_by(&:review_type)
-
4
if review_collection.present?
-
3
seller_reviews = {reviews: review_collection['seller'], meta: {type: 'seller', average_rating: average_rating(review_collection, 'seller'), seller_review_percentages: seller_rating_percentage('seller'), seller_total_rating: seller_total_rating('seller') }} if review_collection['seller'].present?
-
3
catalogue_reviews = {reviews: review_collection['product'], meta: {type: 'product', average_rating: average_rating(review_collection, 'product'), seller_review_percentages: seller_rating_percentage('product'), seller_total_rating: seller_total_rating('product') }} if review_collection['product'].present?
-
3
delivery_reviews = {reviews: review_collection['delivery'], meta: {type: 'delivery', average_rating: average_rating(review_collection, 'delivery'), seller_review_percentages: seller_rating_percentage('delivery'), seller_total_rating: seller_total_rating('delivery') }} if review_collection['delivery'].present?
-
-
3
render json: {seller: seller_reviews, product: catalogue_reviews, delivery: delivery_reviews}, status: :ok
-
else
-
1
render json: { message: "No reviews found with this catalogue id #{params[:category_id]}" }, status: :not_found
-
end
-
end
-
-
1
private
-
-
1
def find_product
-
9
@product = Catalogue.find_by(id: params[:catalogue_id])
-
9
if @product.nil?
-
3
render json: { message: "Product does not exist with id #{params[:catalogue_id]}" },
-
status: :not_found
-
end
-
end
-
-
1
def average_rating(review_collection, type)
-
3
(0...review_collection.count).to_a.each do |record|
-
3
reviews = BxBlockCatalogue::Review.where(review_type: type)
-
3
average_rating = reviews.average(:rating).to_f.round(1)
-
3
return average_rating rescue 0
-
end
-
end
-
-
# def calculate_rating_percent(review_collection)
-
# reviews = BxBlockCatalogue::Review.where(catalogue_id: params[:catalogue_id])
-
# if reviews.present?
-
# product_total_rating = reviews.sum(:rating)
-
# total_ratings = reviews.count
-
# percentages = {}
-
# (1..5).each do |rating|
-
# rating_count = reviews.where(rating: rating).count
-
# percentages[rating] = (rating_count.to_f / total_ratings.to_f) * 100
-
# end
-
-
# (0...review_collection.count).to_a.each do |record|
-
# type = review_collection[record][:meta][:type]
-
# if type == 'product'
-
# review_collection[record][:meta][:product_review_percentage] = percentages
-
# review_collection[record][:meta][:product_total_rating] = product_total_rating
-
# end
-
# end
-
# end
-
# end
-
-
1
def seller_rating_percentage(type)
-
3
ratings = BxBlockCatalogue::Review.where(catalogue_id: params[:catalogue_id], review_type: type)
-
3
total_ratings = ratings.count
-
3
percentages = {}
-
3
(1..5).each do |rating|
-
15
rating_count = ratings.where(rating: rating).count
-
15
percentages[rating] = (rating_count.to_f / total_ratings.to_f) * 100
-
end
-
3
return percentages
-
end
-
-
1
def seller_total_rating(type)
-
3
ratings = BxBlockCatalogue::Review.where(catalogue_id: params[:catalogue_id], review_type: type)
-
3
return ratings.sum(:rating)
-
end
-
-
1
def set_account
-
7
@account = AccountBlock::Account.find_by(id: params[:account_id])
-
7
unless @account
-
render json: {
-
message: "Account with id #{params[:account_id]} doesn't exist"
-
}, status: :not_found
-
end
-
end
-
-
1
def popular_catalog
-
1
@popular_products = @account.catalogues
-
.joins(:review_and_ratings)
-
.group('catalogues.id')
-
.order('AVG(review_and_ratings.rating) DESC')
-
end
-
-
1
def filter_by_category_and_ratings
-
2
@catalogues = @account.catalogues
-
2
if params[:category_id].present?
-
1
@catalogues = @account.catalogues.where(category_id: params[:category_id])
-
1
elsif params[:rating].present?
-
catalogue_id = @account.catalogues.joins(:review_and_ratings).pluck(:id)
-
catalogue_ids = Review.where(catalogue_id: catalogue_id, rating: params[:rating]).pluck(:catalogue_id)
-
@catalogues = Catalogue.where(id: catalogue_ids)
-
else
-
1
@catalogues = @account.catalogues
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class WarehouseCataloguesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :validate_json_web_token, only: [:index, :show, :create, :update, :destroy]
-
1
before_action :get_account, only: [:index, :show, :create, :update, :destroy]
-
1
before_action :check_seller_user, only: [:index, :show, :create, :update, :destroy]
-
1
before_action :set_warehouse
-
1
before_action :find_warehouse_catalogue, only: [ :update, :show, :destroy]
-
-
1
def index
-
2
per_page = params[:per_page].presence&.to_i || 10
-
2
page_number = params[:page].presence&.to_i || 1
-
2
total_count = 0
-
2
@warehouse_catalogues = @warehouse.warehouse_catalogues.all.order(created_at: :desc)
-
2
if params[:search_query].present?
-
1
@warehouse_catalogues = @warehouse.warehouse_catalogues.includes(:catalogue)
-
.includes(:product_variant_group)
-
.where('LOWER(catalogues.sku) LIKE :query OR LOWER(product_variant_groups.product_sku) LIKE :query',query: "%#{params[:search_query]&.strip&.downcase}%").references(:catalogues).references(:product_variant_groups)
-
end
-
-
2
if @warehouse_catalogues.present?
-
2
total_count = @warehouse_catalogues.count
-
2
@warehouse_catalogues = paginate_catalogues(@warehouse_catalogues, page_number, per_page)
-
end
-
-
2
render json: WarehouseCatalogueSerializer.new(@warehouse_catalogues).serializable_hash.merge(total_count: total_count), status: :ok
-
end
-
-
1
def show
-
1
render json: WarehouseCatalogueSerializer.new(@warehouse_catalogue).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@warehouse_catalogue = @warehouse.warehouse_catalogues.new(warehouse_catalogue_params)
-
2
if @warehouse_catalogue.save
-
1
render json: WarehouseCatalogueSerializer.new(@warehouse_catalogue).serializable_hash, status: :created
-
else
-
1
render json: { errors: @warehouse_catalogue.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @warehouse_catalogue.update(warehouse_catalogue_params)
-
1
render json: WarehouseCatalogueSerializer.new(@warehouse_catalogue).serializable_hash, status: :ok
-
else
-
1
render json: { errors: @warehouse_catalogue.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @warehouse_catalogue.destroy
-
1
render json: { message: 'Warehouse catalogue deleted successfully' }, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_warehouse
-
8
@warehouse = @account.warehouses.find(params[:warehouse_id]) unless @account.blank?
-
8
render json: { error: 'Warehouse not found' },status: :not_found unless @warehouse.present?
-
end
-
-
1
def warehouse_catalogue_params
-
4
params.require(:warehouse_catalogue).permit(:product_variant_group_id, :catalogue_id, :stocks)
-
end
-
-
1
def find_warehouse_catalogue
-
4
@warehouse_catalogue = WarehouseCatalogue.find(params[:id])
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class WarehousesController < ApplicationController
-
1
before_action :set_warehouse, only: [:update_seller_warehouse, :delete_seller_warehouse]
-
1
before_action :validate_json_web_token, only: [:create_seller_warehouse, :update_seller_warehouse, :delete_seller_warehouse, :seller_warehouse_listing]
-
1
before_action :get_account, only: [:create_seller_warehouse, :update_seller_warehouse, :delete_seller_warehouse, :seller_warehouse_listing]
-
1
before_action :check_seller_user, only: [:create_seller_warehouse,:update_seller_warehouse, :delete_seller_warehouse, :seller_warehouse_listing]
-
-
1
def index
-
2
@warehouses = Warehouse.all
-
2
render json: @warehouses
-
end
-
-
1
def show
-
@warehouse = Warehouse.find(params[:id])
-
render json: @warehouse
-
end
-
-
1
def create
-
3
@warehouse = Warehouse.new(warehouse_params)
-
-
3
if @warehouse.save
-
2
render json: @warehouse, status: :created
-
else
-
1
render json: @warehouse.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def seller_warehouse_listing
-
1
render json: WarehouseSerializer.new(@account.warehouses), status: :ok
-
end
-
-
1
def create_seller_warehouse
-
2
warehouse = @account.warehouses.new(warehouse_params)
-
2
if warehouse.save
-
1
render json: WarehouseSerializer.new(warehouse).serializable_hash, status: :created
-
else
-
1
render json: { errors: warehouse.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update_seller_warehouse
-
2
if @warehouse.update(warehouse_params)
-
1
catalogue_update_message = update_warehouse_catalogues(@warehouse, params[:warehouse][:catalogue_ids])
-
1
render json: WarehouseSerializer.new(@warehouse).serializable_hash.merge(message: catalogue_update_message), status: :ok
-
else
-
1
render json: { errors: @warehouse.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def delete_seller_warehouse
-
1
if @warehouse.destroy
-
1
render json: { message: 'Warehouse deleted successfully' }, status: :ok
-
end
-
end
-
-
-
# def update
-
# if @warehouse.update(warehouse_params)
-
# render json: @warehouse
-
# else
-
# render json: @warehouse.errors, status: :unprocessable_entity
-
# end
-
# end
-
-
# def destroy
-
# @warehouse.destroy
-
# end
-
-
1
private
-
-
1
def set_warehouse
-
5
@warehouse = Warehouse.find_by(id: params[:warehouse][:id])
-
5
if @warehouse.nil?
-
render json: {
-
message: "Warehouse with id #{params[:warehouse][:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def warehouse_params
-
7
params.require(:warehouse).permit(:warehouse_type, :warehouse_name, :warehouse_address_1,:warehouse_address_2, :contact_number, :contact_person, :processing_days)
-
end
-
-
1
def update_warehouse_catalogues(warehouse, catalogue_ids)
-
1
return if catalogue_ids.nil?
-
-
1
new_ids = catalogue_ids.map(&:to_i).to_set
-
1
current_ids = warehouse.warehouse_catalogues.pluck(:catalogue_id).to_set
-
-
1
to_add = new_ids - current_ids
-
1
to_remove = current_ids - new_ids
-
-
1
return { success: true } if to_add.empty? && to_remove.empty?
-
-
1
WarehouseCatalogue.transaction do
-
1
to_add.each do |id|
-
3
warehouse.warehouse_catalogues.create!(catalogue_id: id, stocks: 5)
-
end
-
1
warehouse.warehouse_catalogues.where(catalogue_id: to_remove.to_a).destroy_all
-
end
-
-
1
{ success: true }
-
rescue ActiveRecord::RecordInvalid => e
-
{ success: false, error: e.message }
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class CategoriesController < ApplicationController
-
1
before_action :load_category, only: [:show]
-
-
1
def show
-
1
render json: CategorySerializer.new(@category).serializable_hash,status: :ok
-
end
-
-
1
def index
-
1
@categories = Category.all
-
-
1
render json: CategorySerializer.new(@categories).serializable_hash, status: :ok
-
end
-
-
1
def search_micro_categories
-
render json: {
-
message: "Search query is empty"
-
2
}, status: :ok and return unless params[:search_query].present?
-
-
2
search_query = "%#{params[:search_query].downcase}%"
-
-
2
@micro_categories = MicroCategory
-
.joins(:category, :sub_category, :mini_category)
-
.where('LOWER(micro_categories.name) LIKE :search_query OR
-
LOWER(categories.name) LIKE :search_query OR
-
LOWER(sub_categories.name) LIKE :search_query OR
-
LOWER(mini_categories.name) LIKE :search_query',
-
search_query: search_query)
-
-
2
render json: MicroCategorySerializer.new(@micro_categories).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def load_category
-
2
@category = Category.find_by(id: params[:id])
-
-
2
if @category.nil?
-
1
render json: {
-
message: "Category doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
end
-
end
-
-
1
module BxBlockCategories
-
1
class CustomFieldsController < ApplicationController
-
1
before_action :load_category, only: [:index,:show_custom_fields]
-
1
before_action :load_category_or_micro_category, only: [:show_custom_fields]
-
-
1
def index
-
1
@custom_fields = CustomField.all
-
-
1
render json: CustomFieldSerializer.new(@custom_fields).serializable_hash, status: :ok
-
end
-
-
1
def show_custom_fields
-
3
custom_fields = []
-
-
3
if @category
-
3
custom_fields.concat(@category.custom_fields)
-
end
-
-
3
if @micro_category
-
1
custom_fields.concat(@micro_category.custom_fields)
-
end
-
-
3
if custom_fields.empty?
-
1
render json: {
-
message: "Custom fields don't exist for this category or microcategory."
-
}, status: :not_found
-
else
-
2
render json: CustomFieldSerializer.new(custom_fields).serializable_hash, status: :ok
-
end
-
end
-
-
-
1
private
-
-
1
def load_category
-
4
@category = Category.find_by(id: params[:category_id])
-
end
-
-
1
def load_category_or_micro_category
-
3
@micro_category = @category.micro_categories.find_by(id: params[:micro_category_id])
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class MicroCategoriesController < ApplicationController
-
1
before_action :load_mini_category
-
1
before_action :load_micro_category, only: [:show]
-
-
1
def show
-
1
render json: MicroCategorySerializer.new(@micro_category).serializable_hash,status: :ok
-
end
-
-
1
def index
-
1
@micro_categories = @mini_category.micro_categories.all
-
-
1
render json: MicroCategorySerializer.new(@micro_categories).serializable_hash, status: :ok
-
end
-
-
1
def list_microcategories_by_minicategory_ids
-
1
@micro_categories = MicroCategory.includes(:mini_category).where(mini_category_id: params[:mini_category_ids])
-
1
render json: MicroCategorySerializer.new(@micro_categories).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def load_micro_category
-
2
@micro_category = @mini_category.micro_categories.find_by(id: params[:id])
-
-
2
if @micro_category.nil?
-
1
render json: {
-
message: "MicroCategory doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def load_mini_category
-
4
@mini_category = MiniCategory.find_by(id: params[:mini_category_id])
-
end
-
-
end
-
end
-
-
1
module BxBlockCategories
-
1
class MiniCategoriesController < ApplicationController
-
1
before_action :load_sub_category
-
1
before_action :load_mini_category, only: [:show]
-
-
1
def show
-
1
render json: MiniCategorySerializer.new(@mini_category).serializable_hash,status: :ok
-
end
-
-
1
def index
-
1
@mini_categories = @sub_category.mini_categories.all
-
-
1
render json: MiniCategorySerializer.new(@mini_categories).serializable_hash, status: :ok
-
end
-
-
1
def list_minicategories_by_subcategory_ids
-
1
@mini_categories = MiniCategory.includes(:sub_category).where(sub_category_id: params[:sub_category_ids])
-
1
render json: MiniCategorySerializer.new(@mini_categories).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def load_mini_category
-
2
@mini_category = @sub_category.mini_categories.find_by(id: params[:id])
-
-
2
if @mini_category.nil?
-
1
render json: {
-
message: "MiniCategory doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def load_sub_category
-
4
@sub_category = SubCategory.find_by(id: params[:sub_category_id])
-
end
-
-
end
-
end
-
-
1
module BxBlockCategories
-
1
class SubCategoriesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :load_category, only: [:show, :index]
-
1
before_action :load_sub_category, only: [:show]
-
-
1
def show
-
1
render json: SubCategorySerializer.new(@sub_category).serializable_hash,status: :ok
-
end
-
-
1
def index
-
1
@sub_categories = @category.sub_categories.all
-
-
1
render json: SubCategorySerializer.new(@sub_categories).serializable_hash, status: :ok
-
end
-
-
1
def list_sub_categories_from_catalogues
-
2
deal = BxBlockCatalogue::Deal.all.active_deals.find_by(id: params[:deal_id])
-
-
2
return render json: { error: "Deal not found" }, status: :not_found unless deal.present?
-
-
1
if deal.present?
-
1
catalogues_ids = catalogues_by_active_deals(params[:deal_id])
-
1
@sub_categories = SubCategory.includes(:catalogues).where(catalogues: {id: catalogues_ids})
-
1
render json: SubCategorySerializer.new(@sub_categories).serializable_hash, status: :ok
-
end
-
-
end
-
-
1
def list_subcategories_by_category_ids
-
1
@sub_categories = SubCategory.includes(:category).where(parent_id: params[:category_ids])
-
1
render json: SubCategorySerializer.new(@sub_categories).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def load_sub_category
-
2
@sub_category = @category.sub_categories.find_by(id: params[:id])
-
-
2
if @sub_category.nil?
-
1
render json: {
-
message: "SubCategory doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def load_category
-
4
@category = Category.find(params[:category_id])
-
end
-
-
end
-
end
-
-
1
module BxBlockContactUs
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
-
# rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
# private
-
-
# def not_found
-
# render :json => {'errors' => ['Record not found']}, :status => :not_found
-
# end
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ContactsController < ApplicationController
-
#create contact us
-
1
def create
-
2
@contact = Contact.new(contact_params)
-
-
2
if @contact.save
-
1
BxBlockEmailNotifications::SendEmailNotificationService.with(to: "support@byezzy.com",from: "buyer_contact@byezzy.com", contact: @contact,subject: "New Contact - #{@contact.contact_type.to_s.capitalize}",file: 'new_contact_notification').notification.deliver_now
-
-
1
render json: ContactSerializer.new(@contact).serializable_hash, status: :created
-
else
-
1
render json: {errors: [
-
{contact: @contact.errors.full_messages},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
def contact_params
-
2
params.permit(:title, :email, :description, :contact_type, :image)
-
end
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class CouponCodesController < ApplicationController
-
1
before_action :validate_json_web_token
-
1
before_action :check_seller_account, only: %i[show index]
-
1
before_action :load_coupon, only: %i[show]
-
-
-
1
def show
-
1
render json: CouponCodeSerializer.new(@coupon).serializable_hash, status: :ok
-
end
-
-
#GET /coupons
-
1
def index
-
1
render json: CouponCodeSerializer.new(CouponCode.active), status: :ok
-
end
-
-
1
private
-
-
1
def check_seller_account
-
3
account = AccountBlock::Account.find_by(id: @token.id)
-
3
if account.nil? && !account&.user_type == 'seller'
-
return render json: {message: 'You are not authorized to access this action'}
-
end
-
end
-
-
1
def load_coupon
-
2
@coupon = CouponCode.find_by(id: params[:id])
-
2
if @coupon.nil?
-
1
render json: {
-
message: "Coupon with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
-
1
module BxBlockCouponCg
-
1
class SubscribeCouponsController < ApplicationController
-
1
before_action :validate_json_web_token
-
1
before_action :check_seller_account, only: %i[create update destroy index]
-
1
before_action :get_subscribe_coupon, only: %i[update destroy]
-
-
1
def index
-
1
serializer = SubscribeCouponSerializer.new(@account.subscribe_coupons)
-
1
render json: serializer, status: :ok
-
end
-
-
1
def create
-
2
subscribe_coupon = SubscribeCoupon.new(subscribe_coupons_params.merge(account_id: @account.id))
-
2
if subscribe_coupon.save
-
1
render json: SubscribeCouponSerializer.new(subscribe_coupon).serializable_hash, status: :created
-
else
-
1
render json: { errors: format_activerecord_errors(subscribe_coupon.errors) },status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
1
if @subscribe_coupon.update(subscribe_coupons_params)
-
1
render json: SubscribeCouponSerializer.new(@subscribe_coupon).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@subscribe_coupon.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @subscribe_coupon.destroy
-
1
render json: { message: 'Successfully deleted the SubscribeCoupon' }, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@subscribe_coupon.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
-
1
private
-
-
1
def subscribe_coupons_params
-
3
params.permit(:catalogue_id, :coupon_code_id)
-
end
-
-
1
def get_subscribe_coupon
-
2
@subscribe_coupon = SubscribeCoupon.find_by(id: params[:id])
-
2
if @subscribe_coupon.nil?
-
render json: {
-
message: "Subscribe coupon with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def check_seller_account
-
5
@account = AccountBlock::Account.find_by(id: @token.id)
-
5
if @account&.user_type == 'buyer'
-
return render json: {message: 'You are not authorized to access this action'}
-
end
-
end
-
end
-
end
-
-
1
module BxBlockCustomAds
-
1
class AdvertisementsController < ApplicationController
-
1
before_action :find_advertisement, only: [:show]
-
1
def index
-
1
advertisements = Advertisement&.active
-
1
render json: {
-
advertisements: advertisements,
-
message: "Successfully loaded"
-
}
-
end
-
-
# def create
-
# advertisement = Advertisement.new(advertisement_params)
-
# advertisement.seller_account_id =
-
# BxBlockCustomForm::SellerAccount.find_by(
-
# account_id: current_user.id
-
# ).id
-
# if advertisement.save
-
# render json: {
-
# advertisement: advertisement,
-
# message: "Successfully created"
-
# }, status: :created
-
# else
-
# render json: {
-
# errors: format_activerecord_errors(advertisement.errors)
-
# }, status: :unprocessable_entity
-
# end
-
# end
-
-
1
def show
-
1
render json: {
-
advertisement: @advertisement,
-
message: "Successfully loaded"
-
}
-
end
-
-
1
private
-
-
1
def find_advertisement
-
2
@advertisement = Advertisement.find(params[:id])
-
end
-
-
# def advertisement_params
-
# params.require(:advertisement).permit(
-
# :name, :description, :duration, :advertisement_for, :status, :banner
-
# )
-
# end
-
end
-
end
-
1
module BxBlockCustomAds
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
module BxBlockDashboard
-
1
class AuthorFavoriteBooksController < ApplicationController
-
1
before_action :load_author_favorite_book, only: [:show]
-
-
1
def index
-
2
@author_favorite_books = AuthorFavoriteBook.all
-
-
2
render json: AuthorFavoriteBookSerializer.new(@author_favorite_books)
-
end
-
-
1
def show
-
1
render json: AuthorFavoriteBookSerializer.new(@author_favorite_book)
-
end
-
-
1
def latest_author_favorite
-
1
@author_favorite_book = AuthorFavoriteBook.order(created_at: :desc).find_by(status: true)
-
-
1
render json: AuthorFavoriteBookSerializer.new(@author_favorite_book)
-
end
-
-
1
private
-
-
1
def load_author_favorite_book
-
1
@author_favorite_book = AuthorFavoriteBook.find_by(id: params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class BannersController < ApplicationController
-
1
before_action :load_banners, only: %i[header_slideshow_index header_single_images_index middle_slideshow_index middle_single_images_index footer_single_images_index]
-
-
1
def header_slideshow_index
-
1
render_banners
-
end
-
-
1
def header_single_images_index
-
1
render_banners
-
end
-
-
1
def middle_slideshow_index
-
2
unless params[:group_name]
-
1
return render json: {
-
message: "group_name params is missing send middle_group_1 or 2"
-
}, status: :not_found
-
end
-
1
render_banners
-
end
-
-
1
def middle_single_images_index
-
1
render_banners
-
end
-
-
1
def footer_single_images_index
-
1
render_banners
-
end
-
-
1
def top_banner
-
1
top_banner = Banner.find_by(banner_type: "top_banner", status: true)
-
1
render json: BannerSerializer.new(top_banner).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def load_banners
-
6
if section_param == 'middle'
-
3
@banners = Banner.where(section: 'middle', banner_type: banner_type_param, banner_group_id: banner_group_id_param)
-
else
-
3
@banners = Banner.where(section: section_param, banner_type: banner_type_param)
-
end
-
end
-
-
1
def section_param
-
9
case action_name
-
when 'header_slideshow_index', 'header_single_images_index'
-
4
'header'
-
when 'middle_slideshow_index', 'middle_single_images_index'
-
3
'middle'
-
else
-
2
'footer'
-
end
-
end
-
-
1
def banner_type_param
-
6
case action_name
-
when 'header_slideshow_index', 'middle_slideshow_index'
-
3
'slideshow'
-
else
-
3
'single_image'
-
end
-
end
-
-
1
def render_banners
-
5
render json: BannerSerializer.new(@banners).serializable_hash, status: :ok
-
end
-
-
1
def banner_group_id_param
-
3
banner_group = BannerGroup.find_by(group_name: params[:group_name])
-
3
banner_group.id if banner_group
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class GlobalSearchesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :catalogues
-
-
1
def search
-
13
return render_no_product_found if params[:search_keyword].blank?
-
-
12
catalogues = product_search_by_tbc(params[:search_keyword], @catalogues) || []
-
12
catalogues = filter_out_of_stock(catalogues) if out_of_stock_filter?
-
12
min_range, max_range = get_min_max_value(catalogues)
-
-
12
catalogues = apply_category_filters(catalogues) if category_filter_present?
-
12
catalogues = apply_price_filters(catalogues, params[:min_price], params[:max_price]) if price_filters_present? && catalogues.present?
-
12
catalogues = filter_by_custom_field_values(catalogues, params[:custom_field_values]) if params[:custom_field_values].present?
-
12
catalogues = filter_by_ratings(catalogues,params[:filter_by_rating]) if params[:filter_by_rating].present?
-
12
catalogues = filter_by_colors(catalogues, params[:color_filter]) if params[:color_filter].present?
-
-
12
catalogues = sort_catalogues(catalogues, params[:sort_by]) if sort_by_present?
-
12
per_page = params[:per_page].presence || 50
-
12
page = params[:page].presence || 1
-
-
12
total_count = catalogues.count
-
-
12
catalogues = paginate_catalogues(catalogues, page, per_page) if catalogues.present?
-
-
12
render_search_results(catalogues, min_range, max_range, nil, total_count)
-
end
-
-
1
def brands_filter_lists
-
4
return render_no_result_found if params[:search_keyword].blank? && params[:trending_slider].blank?
-
-
3
catalogues = fetched_catalogues(params[:trending_slider], params[:search_keyword])
-
-
3
if catalogues.present?
-
2
brands = extract_brands_from_catalogues(catalogues)
-
2
render json: BxBlockCatalogue::BrandSerializer.new(brands).serializable_hash, status: :ok
-
else
-
1
render_no_result_found
-
end
-
end
-
-
1
def categories_filter_lists
-
4
return render_no_result_found if params[:search_keyword].blank? && params[:trending_slider].blank?
-
-
3
catalogues = fetched_catalogues(params[:trending_slider], params[:search_keyword])
-
-
3
if catalogues.present?
-
2
categories = extract_categories_from_catalogues(catalogues)
-
2
render json: BxBlockCategories::CategorySerializer.new(categories).serializable_hash, status: :ok
-
else
-
1
render_no_result_found
-
end
-
end
-
-
1
private
-
-
1
def catalogues
-
21
@catalogues = BxBlockCatalogue::Catalogue.joins(:product_content).where(status: true)
-
end
-
-
1
def apply_category_filters(catalogues)
-
conditions = {
-
9
category_id: params[:category_ids],
-
sub_category_id: params[:sub_category_ids],
-
mini_category_id: params[:mini_category_ids],
-
micro_category_id: params[:micro_category_ids],
-
brand_id: params[:brand_ids]
-
}
-
-
54
filtered_conditions = conditions.reject { |_, value| value.blank? }
-
-
9
catalogues.where(filtered_conditions)
-
end
-
-
1
def category_filter_present?
-
12
params[:category_ids].present? || params[:sub_category_ids].present? || params[:mini_category_ids].present? || params[:micro_category_ids].present? || params[:brand_ids].present?
-
end
-
-
1
def price_filters_present?
-
12
params[:min_price].present? && params[:max_price].present?
-
end
-
-
1
def sort_by_present?
-
12
params[:sort_by].present?
-
end
-
-
1
def filter_out_of_stock(catalogues)
-
1
catalogues.where('COALESCE(stocks, 0) <= ?', 0)
-
end
-
-
1
def out_of_stock_filter?
-
12
params[:out_of_stocks]&.to_s == 'true'
-
end
-
1
def extract_brands_from_catalogues(catalogues)
-
2
catalogues.map(&:brand).uniq
-
end
-
-
1
def extract_categories_from_catalogues(catalogues)
-
2
catalogues.map(&:category).uniq
-
end
-
-
1
def extract_catalogues_from_trending_slider(slider)
-
2
trending_product = TrendingProduct.find_by(slider: slider)
-
2
catalogue_ids = trending_product&.catalogues&.pluck(:id) || []
-
2
BxBlockCatalogue::Catalogue.where(id: catalogue_ids)
-
end
-
-
1
def fetched_catalogues(trending_slider, search_keyword)
-
6
if trending_slider.present?
-
2
extract_catalogues_from_trending_slider(trending_slider)
-
else
-
4
product_search_by_tbc(search_keyword, @catalogues)
-
end
-
end
-
-
1
def product_search_by_tbc(product_keyword, catalogues_scope)
-
16
product_keyword = "%#{product_keyword&.strip&.downcase}%"
-
16
search_columns = %w[ catalogues.product_title brands.brand_name categories.name
-
sub_categories.name mini_categories.name micro_categories.name]
-
112
query = search_columns.map { |col| "LOWER(#{col}) LIKE :query"}.join(" or ")
-
16
catalogues_scope.joins(:brand, :category, :sub_category, :mini_category, :micro_category)
-
.where(query, query: product_keyword)
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class HeaderCategoriesController < ApplicationController
-
1
before_action :load_header_category, only: [:show]
-
-
1
def index
-
1
@header_categories = HeaderCategory.all.order(sequence_no: :asc)
-
-
1
render json: HeaderCategorySerializer.new(@header_categories)
-
end
-
-
1
def show
-
1
render json: HeaderCategorySerializer.new(@header_category)
-
end
-
-
1
private
-
-
1
def load_header_category
-
1
@header_category = HeaderCategory.find_by(id: params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class MostPopularCategoriesController < ApplicationController
-
1
before_action :load_popular_category, only: [:show]
-
-
1
def index
-
1
@popular_categories = MostPopularCategory.all.order(sequence_no: :asc)
-
-
1
render json: MostPopularCategorySerializer.new(@popular_categories)
-
end
-
-
1
def show
-
1
render json: MostPopularCategorySerializer.new(@popular_category)
-
end
-
-
1
private
-
-
1
def load_popular_category
-
1
@popular_category = MostPopularCategory.find_by(id: params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TopBrandsController < ApplicationController
-
1
before_action :load_top_brand, only: [:show]
-
-
1
def index
-
1
@top_brands = TopBrand.all.order(sequence_no: :asc)
-
-
1
render json: TopBrandSerializer.new(@top_brands)
-
end
-
-
1
def show
-
1
render json: TopBrandSerializer.new(@top_brand)
-
end
-
-
1
private
-
-
1
def load_top_brand
-
1
@top_brand = TopBrand.find_by(id: params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TrendingProductsController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
-
1
before_action :load_trending_product, only: [:show]
-
-
1
def index
-
2
if params[:slider].present?
-
1
@trending_products = TrendingProduct.where(slider: params[:slider])
-
else
-
1
@trending_products = TrendingProduct.all
-
end
-
-
2
render json: TrendingProductSerializer.new(@trending_products)
-
end
-
-
1
def show
-
1
render json: TrendingProductSerializer.new(@trending_product)
-
end
-
-
1
def list_trending_products
-
-
6
return render json: { message: "missing slider in params" }, status: :unprocessable_entity if params[:slider].blank?
-
-
5
@trending_product = TrendingProduct.find_by(slider: params[:slider])
-
-
5
if @trending_product.nil?
-
1
return render json: { message: "No trending products found for the given slider" }, status: :not_found
-
end
-
-
4
catalogue_ids = @trending_product.catalogues.pluck(:id)
-
4
catalogues = BxBlockCatalogue::Catalogue.where(id: catalogue_ids)
-
-
4
if params[:out_of_stocks]&.to_s == 'true'
-
1
catalogues = catalogues.where('COALESCE(stocks, 0) <= ?', 0)
-
end
-
-
4
min_range, max_range = get_min_max_value(catalogues)
-
-
4
apply_category_filters(catalogues)
-
-
4
if params[:custom_field_values].present?
-
1
catalogues = filter_by_custom_field_values(catalogues, params[:custom_field_values])
-
end
-
-
4
if params[:filter_by_rating].present?
-
3
catalogues = filter_by_ratings(catalogues,params[:filter_by_rating])
-
end
-
-
4
if params[:min_price].present? && params[:max_price].present?
-
3
catalogues = apply_price_filters(catalogues, params[:min_price], params[:max_price])
-
end
-
-
4
if params[:color_filter].present?
-
3
catalogues = filter_by_colors(catalogues, params[:color_filter])
-
end
-
-
4
per_page = params[:per_page].presence || 50
-
4
page = params[:page].presence || 1
-
-
4
if params[:sort_by].present?
-
3
catalogues = sort_catalogues(catalogues, params[:sort_by])
-
end
-
-
4
total_count = catalogues.count
-
-
4
catalogues = paginate_catalogues(catalogues, page, per_page)
-
-
-
4
render_results(@trending_product, catalogues, min_range, max_range, total_count)
-
end
-
-
1
def render_results(trending_product, catalogues, min_range, max_range, total_count = 0)
-
4
render json: BxBlockCatalogue::CatalogueSerializer.new(catalogues).serializable_hash.merge({ trending_product: trending_product, min_range: min_range,
-
max_range: max_range,
-
total_count: total_count} ), status: :ok
-
end
-
-
1
private
-
-
1
def load_trending_product
-
1
@trending_product = TrendingProduct.find_by(id: params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class WeeklyHomieeDealsController < ApplicationController
-
1
before_action :load_weekly_homiee_deal, only: [:show]
-
-
1
def index
-
1
@weekly_homiee_deals = WeeklyHomieeDeal.all
-
-
1
render json: WeeklyHomieeDealSerializer.new(@weekly_homiee_deals)
-
end
-
-
1
def show
-
1
render json: WeeklyHomieeDealSerializer.new(@weekly_homiee_deal)
-
end
-
-
1
def latest_weekly_deal
-
1
@weekly_homiee_deal = WeeklyHomieeDeal.all.active_homiee_deals.order(created_at: :desc)&.first
-
-
1
render json: WeeklyHomieeDealSerializer.new(@weekly_homiee_deal)
-
end
-
-
1
private
-
-
1
def load_weekly_homiee_deal
-
1
@weekly_homiee_deal = WeeklyHomieeDeal.find_by(id: params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockFavourites
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
1
def current_user
-
6
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
end
-
end
-
1
module BxBlockFavourites
-
1
class FavouritesController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
-
1
def index
-
3
per_page = params[:per_page].presence&.to_i || 10
-
3
page = params[:page].presence&.to_i || 1
-
3
total_count = 0
-
-
3
favourites = Favourite.where(user_id: current_user.id)
-
-
3
if favourites.present?
-
-
2
catalogue_ids = favourites.pluck(:favouriteable_id)
-
-
2
catalogues = BxBlockCatalogue::Catalogue.includes(:product_content).where(id: catalogue_ids)
-
-
2
if params[:sort_by].present?
-
1
catalogues = sort_catalogues(catalogues, params[:sort_by]).pluck(:id)
-
-
1
sanitized_sql = ActiveRecord::Base.sanitize_sql_array(["array_position(array[?], favouriteable_id::int)", catalogues])
-
-
1
sorted_favourites = favourites.order(Arel.sql(sanitized_sql))
-
else
-
1
sorted_favourites = favourites.order(created_at: :desc)
-
end
-
-
2
if sorted_favourites
-
# sorting favourites
-
2
total_count = sorted_favourites.count
-
2
sorted_favourites = paginate_catalogues(sorted_favourites, page, per_page)
-
end
-
-
2
render json: FavouriteSerializer.new(sorted_favourites).serializable_hash.merge(total_count: total_count),
-
status: :ok
-
else
-
1
render json: [],
-
status: :not_found
-
end
-
end
-
-
1
def create
-
2
favouriteable_type = find_favouriteable_type(params[:favouriteable_id])
-
-
2
existing_favourite = Favourite.find_by(
-
favouriteable_id: params[:favouriteable_id],
-
user_id: current_user.id,
-
favouriteable_type: favouriteable_type,
-
product_variant_group_id: params[:product_variant_group_id]
-
)
-
-
2
unless existing_favourite
-
-
1
favourite = Favourite.new(
-
favourites_params.merge(
-
user_id: current_user.id,
-
favouriteable_type: favouriteable_type,
-
product_variant_group_id: params[:product_variant_group_id]
-
)
-
)
-
-
1
if favourite.save
-
1
render json: BxBlockFavourites::FavouriteSerializer.new(favourite).serializable_hash,
-
status: :ok
-
else
-
render json: { errors: favourite.errors },
-
status: :unprocessable_entity
-
end
-
else
-
1
render json: { message: "Product already exist in wishlist" },
-
status: :ok
-
end
-
end
-
-
1
def destroy
-
2
favourite = BxBlockFavourites::Favourite.find(params[:id])
-
1
if favourite.destroy
-
1
render json: { message: "Destroy successfully" },
-
status: :ok
-
end
-
end
-
-
1
private
-
-
1
def find_favouriteable_type(favouriteable_id)
-
2
if params[:favouriteable_id].present?
-
2
catalogue_exists = BxBlockCatalogue::Catalogue.exists?(id: params[:favouriteable_id])
-
2
'BxBlockCatalogue::Catalogue' if catalogue_exists
-
end
-
end
-
-
1
def favourites_params
-
1
params.permit(:favouriteable_id, :user_id, :favouriteable_type, :product_variant_group_id)
-
end
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class PasswordsController < ApplicationController
-
1
before_action :decode_token, only: [:reset_password, :current_password]
-
-
1
def forgot_password
-
6
return render json: { errors: [{ profile: 'Email id should not be blank', }], }, status: :unprocessable_entity if create_params[:email].blank?
-
-
5
account = AccountBlock::Account.find_by(email: create_params[:email].downcase.strip, user_type: create_params[:user_type])
-
-
5
return render_invalid_email if account.blank?
-
-
3
token = BuilderJsonWebToken.encode(account.id,10.minutes.from_now)
-
3
ForgotPasswordMailer.with(account: account, host: request.base_url,token: token).reset_email.deliver_now
-
3
render json: { message: { forgot_password: 'ResetPassword link has been successfully sent to the mail id',}}, status: :created
-
end
-
-
1
def reset_password
-
6
token = create_params[:token] || params[:token]
-
6
if token.blank? || create_params[:new_password].blank? || create_params[:confirm_password].blank?
-
1
return render json: {errors: [{ reset_password: 'Token, New Password, and Confirm Password are required', }],}, status: :unprocessable_entity
-
end
-
5
return render_invalid_token unless @decoded_token
-
5
account = AccountBlock::Account.find_by(id: @decoded_token.id)
-
-
5
if @decoded_token.expiration < 10.minutes.ago || token == account.reset_token
-
1
return render json: {
-
errors: [{ token: 'Token has expired or has already been used',}],
-
}, status: :unprocessable_entity
-
end
-
-
4
if create_params[:new_password] != create_params[:confirm_password]
-
2
return render json: {
-
errors: [{reset_password: 'New Password and Confirm Password do not match',}],
-
}, status: :unprocessable_entity
-
end
-
-
2
password_validation = AccountBlock::PasswordValidation.new(create_params[:new_password])
-
2
if password_validation.invalid?
-
return render json: {
-
errors: [{password: password_validation.error_message.full_messages.first}],
-
}, status: :unprocessable_entity
-
end
-
-
2
account.password = create_params[:new_password]
-
2
account.reset_token = token
-
2
account.reset_token_used_at = Time.now
-
2
if account.save(context: :update_password)
-
2
render json: AccountBlock::AccountSerializer.new(account, meta: { message: "Password has changed successfully" }).serializable_hash, status: :ok
-
else
-
render json: { errors: account.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def current_password
-
3
if params[:data][:token].blank? || params[:data][:current_password].blank?
-
return render json: {
-
errors: [{ reset_password: 'Token and Current Password are required', }],
-
}, status: :unprocessable_entity
-
end
-
-
3
return render_invalid_token unless @decoded_token
-
3
account = AccountBlock::Account.find_by(id: @decoded_token.id)
-
3
return render json: { errors: [{token: "Token expired",}], }, status: :unprocessable_entity if account.nil? || @decoded_token.expiration < 10.minutes.ago
-
3
if BCrypt::Password.new(account.password_digest) == params[:data][:current_password]
-
1
render json: {
-
data: true, message: "Current Password is correct"
-
}, status: :ok
-
else
-
2
render json: {
-
data: false, message: 'Current Password is not correct'
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def decode_token
-
10
token = params[:token] || create_params[:token]
-
10
return if token.blank?
-
-
begin
-
9
@decoded_token = BuilderJsonWebToken.decode(token)
-
1
rescue JWT::DecodeError => e
-
1
return render_invalid_token
-
end
-
end
-
-
1
def render_invalid_token
-
1
render json: {
-
errors: [{ token: 'Invalid token' }]
-
}, status: :bad_request
-
end
-
-
1
def render_invalid_email
-
2
render json: {
-
errors: [{
-
profile: 'The email is not registered or Email id is not valid',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
1
def create_params
-
54
params.require(:data)
-
.permit(*[
-
:user_type,
-
:email,
-
:full_phone_number,
-
:token,
-
:otp_code,
-
:new_password,
-
:confirm_password,
-
])
-
end
-
end
-
end
-
1
module BxBlockInvoicebilling
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockInvoicebilling
-
1
class InvoiceBillingsController < ApplicationController
-
-
1
before_action :find_order
-
1
before_action :find_user
-
-
1
def invoice_pdf
-
1
@invoice = InvoiceBilling.create(order: @order, order_item: @order_item, customer: @user)
-
1
pdf = Prawn::Document.new
-
1
generate_invoice_pdf(pdf, @order, @order_item, @invoice, @transaction_details)
-
1
pdf.render_file("#{Rails.root}/tmp/invoice-#{Time.now.strftime("%d-%m-%Y-%H-%M")}.pdf")
-
-
1
@invoice.invoice_pdf.attach(io: File.open("#{Rails.root}/tmp/invoice-#{Time.now.strftime("%d-%m-%Y-%H-%M")}.pdf"), filename: "invoice-#{Time.now.strftime("%d-%m-%Y-%H-%M")}.pdf")
-
-
1
render json: BxBlockInvoicebilling::InvoiceBillingSerializer.new(@invoice).serializable_hash
-
end
-
-
1
private
-
-
1
def find_order
-
3
@order = BxBlockShoppingCart::Order.all.includes(:order_status).where.not('order_statuses.status': ['on_going','ordered','scheduled']).find_by(id: params[:order_id])
-
3
render json: { error: "Order not found or not delivered" }, status: :not_found and return unless @order
-
2
@order_item = @order.order_items.find params[:order_item_id]
-
2
@transaction_details = get_transaction_details(@order) ? JSON.parse(get_transaction_details(@order)) : get_transaction_details(@order)
-
end
-
-
1
def get_transaction_details(order)
-
4
if order.transaction_id
-
4
url = URI("https://secure.telr.com/gateway/order.json")
-
4
http = Net::HTTP.new(url.host, url.port)
-
4
http.use_ssl = true
-
4
request = Net::HTTP::Post.new(url)
-
4
request["accept"] = 'application/json'
-
4
request["Content-Type"] = 'application/json'
-
-
4
request.body = {"method":"check", "store": ENV['TELR_STORE_ID'], "authkey": ENV['TELR_AUTH_KEY'], "order":{"ref": order.transaction_id }}.to_json
-
-
4
response = http.request(request)
-
4
response.read_body
-
end
-
end
-
-
1
def find_user
-
2
@user = AccountBlock::Account.find_by(id: @token.id)
-
2
render json: { error: "User Invalid" }, status: :not_found and return unless @user && @order.customer == @user
-
end
-
-
1
def generate_invoice_pdf(pdf, order, order_item, invoice, transaction_details)
-
-
1
pdf.font_families.update("Roboto" => {
-
normal: "#{Rails.root}/lib/fonts/open_sans/static/OpenSans-Regular.ttf",
-
bold: "#{Rails.root}/lib/fonts/open_sans/static/OpenSans-Bold.ttf"
-
})
-
-
1
pdf.font "Roboto"
-
-
1
pdf.text "Invoice", size: 30, style: :bold, align: :center
-
-
1
pdf.move_down 20
-
1
pdf.bounding_box([0, pdf.cursor], width: pdf.bounds.width / 2) do
-
1
pdf.text "Sold By:", size: 15, style: :bold
-
1
pdf.text "Name: #{order_item.seller.full_name}"
-
1
pdf.text "Company: #{order_item.seller.company_or_store_name}"
-
1
pdf.text "Email: #{order_item.seller.email}"
-
1
pdf.text "Phone no: #{order_item.seller.full_phone_number}"
-
end
-
-
1
pdf.move_down 20
-
1
y_position = pdf.cursor
-
1
pdf.bounding_box([0, y_position], width: pdf.bounds.width / 2) do
-
1
pdf.text "Billing Address:", size: 15, style: :bold
-
1
pdf.text "#{order.shipping_first_name} #{order.shipping_last_name}"
-
1
pdf.text "#{order.shipping_address_1}"
-
1
pdf.text "#{order.shipping_address_2}" if order.shipping_address_2.present?
-
1
pdf.text "#{order.shipping_city}, #{order.shipping_state}, #{order.shipping_zip_code}"
-
end
-
-
1
pdf.bounding_box([300, y_position], width: pdf.bounds.width / 2) do
-
1
pdf.text "Shipping Address:", size: 15, style: :bold
-
1
pdf.text "#{order.shipping_first_name} #{order.shipping_last_name}"
-
1
pdf.text "#{order.shipping_address_1}"
-
1
pdf.text "#{order.shipping_address_2}" if order.shipping_address_2.present?
-
1
pdf.text "#{order.shipping_city}, #{order.shipping_state}, #{order.shipping_zip_code}"
-
end
-
-
1
pdf.move_down 20
-
1
pdf.bounding_box([0, pdf.cursor], width: pdf.bounds.width / 2) do
-
1
pdf.text "Order Information", size: 15, style: :bold
-
1
pdf.text "Order ID: #{order.order_number}"
-
1
pdf.text "Order Date: #{order.order_placed_at&.strftime('%Y-%m-%d')}"
-
end
-
1
pdf.move_up 50
-
1
pdf.bounding_box([400, pdf.cursor], width: pdf.bounds.width / 2) do
-
1
pdf.text "Invoice Details", size: 15, style: :bold
-
1
pdf.text "Invoice ID: #{invoice.invoice_number}"
-
1
pdf.text "Invoice Date: #{order.delivered_at&.strftime('%Y-%m-%d')}"
-
end
-
-
1
pdf.move_down 20
-
1
pdf.text "Order Item Information", size: 15, style: :bold
-
1
pdf.move_down 10
-
1
pdf.table([["S.No", "Item", "Quantity", "Price", "Total"]] +
-
[[1, order_item.catalogue.product_title, order_item.quantity, "AED #{order_item.price}", "AED #{order_item.quantity * order_item.price}"]],
-
header: true,
-
width: pdf.bounds.width) do
-
1
row(0).font_style = :bold
-
1
row(0).background_color = "DDDDDD"
-
1
self.cell_style = { borders: [] }
-
end
-
-
1
total_price = order_item.quantity * order_item.price
-
-
1
pdf.move_down 20
-
1
pdf.text "Amount In Words: #{total_price.to_words.humanize.capitalize} dirhams", size: 10, style: :bold
-
-
1
if transaction_details
-
1
pdf.move_down 20
-
1
pdf.table([["Transaction ID", "Date & Time", "Invoice value", "Mode Of paymemt"]] +
-
[[transaction_details.dig('order','transaction','ref'),transaction_details.dig("order","transaction","date"),"AED #{total_price}",transaction_details.dig("order","card","type")]],
-
header: true,
-
width: pdf.bounds.width) do
-
1
row(0).font_style = :bold
-
1
row(0).background_color = "DDDDDD"
-
1
self.cell_style = { borders: [] }
-
end
-
end
-
end
-
-
end
-
end
-
1
module BxBlockLogin
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
module BxBlockLogin
-
1
class LoginsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token, only:[:send_login_otp]
-
1
def create
-
8
case params[:data][:type] #### rescue invalid API format
-
when 'sms_account', 'email_account', 'social_account'
-
7
account = OpenStruct.new(jsonapi_deserialize(params))
-
7
account.type = params[:data][:type]
-
7
account.user_type = params[:data][:user_type]
-
-
7
output = AccountAdapter.new
-
-
7
output.on(:account_not_found) do |account|
-
1
render json: {
-
errors: [{
-
failed_login: 'The email is not register or not activated',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
7
output.on(:failed_login) do |account|
-
1
render json: {
-
errors: [{
-
failed_login: 'Email or Password incorrect please try again',
-
}],
-
}, status: :unauthorized
-
end
-
-
7
output.on(:successful_login) do |account, token, refresh_token, document_status, last_visited_at, first_time_login|
-
5
if account.profile_picture.attached?
-
1
image_url = ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(account.profile_picture, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(account.profile_picture, only_path: true)
-
else
-
4
image_url = nil
-
end
-
-
5
render json: {meta: {
-
token: token,
-
refresh_token: refresh_token,
-
id: account.id,
-
full_name: account.full_name,
-
email: account.email,
-
full_phone_number: account.full_phone_number,
-
user_type: account.user_type,
-
document_status: document_status,
-
last_visited_at: last_visited_at,
-
first_time_login: first_time_login,
-
language: account.language,
-
profile_picture: image_url
-
}}
-
end
-
-
7
output.login_account(account)
-
else
-
1
render json: {
-
errors: [{
-
account: 'Invalid Account Type',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def send_login_otp
-
1
@sms_otp = AccountBlock::SmsOtp.new(jsonapi_deserialize(params))
-
1
email_acc = AccountBlock::Account.find_by(full_phone_number: Phonelib.parse(@sms_otp.full_phone_number).sanitized, user_type: 'seller') ||
-
AccountBlock::Account.find_by(full_phone_number: Phonelib.parse(@sms_otp.full_phone_number).sanitized, user_type: 'buyer')
-
1
if @sms_otp.save
-
1
if email_acc
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: email_acc, pin: @sms_otp.pin, subject: 'OTP for your Byezzy Account', file: 'signup_notification')
-
.notification.deliver_now
-
end
-
1
render json: AccountBlock::SmsOtpSerializer.new(@sms_otp, meta: {
-
token: BuilderJsonWebToken.encode(@sms_otp.id)
-
}).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@sms_otp.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class AnchantoWmsController < ApplicationController
-
1
skip_before_action :validate_json_web_token,
-
only: %i[event_consignment_status_update_in_wms event_b2c_shipment_status_update_in_wms
-
event_grn_status_update_in_wms]
-
1
skip_before_action :get_user,
-
only: %i[event_grn_status_update_in_wms event_consignment_status_update_in_wms
-
event_b2c_shipment_status_update_in_wms]
-
-
1
before_action :check_seller, only: %i[create_wms_product create_consignment_order b2c_order_index]
-
1
before_action :find_catalogue, only: %i[create_wms_product create_consignment_order]
-
1
before_action :find_order, only: %i[create_b2c_order]
-
1
before_action :validate_params, only: %i[create_wms_product create_consignment_order]
-
-
3
after_action :save_product_response, only: %i[create_wms_product], if: -> { successful_response? }
-
4
after_action :save_consignment_response, only: %i[create_consignment_order], if: -> { successful_response? }
-
-
1
def create_wms_product
-
2
product_create_api = 'https://uatapi.anchanto.com/rest/v1/products'
-
2
http_method = 'POST'
-
-
2
request_body = product_details(@catalogue)
-
-
2
response, response_code = send_request(product_create_api, request_body, http_method)
-
2
handle_response(response, response_code)
-
end
-
-
1
def create_consignment_order
-
3
create_consignment_api = 'https://uatapi.anchanto.com/rest/v1/consignments'
-
3
@quantity = params[:quantity]
-
3
http_method = 'POST'
-
-
3
return render json: { message: 'Missing quantity' }, status: :unprocessable_entity if @quantity.blank?
-
-
2
request_body = consignment_details(@catalogue, @quantity)
-
2
response, response_code = send_request(create_consignment_api, request_body, http_method)
-
-
2
handle_response(response, response_code)
-
end
-
-
1
def create_b2c_order
-
2
create_b2c_order_api = 'https://uatapi.anchanto.com/rest/v1/b2c/orders'
-
2
http_method = 'POST'
-
-
3
order_items = @order.order_items.select { |item| item&.catalogue&.fulfilled_type == 'byezzy' }
-
-
2
if order_items.any?
-
1
request_body = b2c_order_details(@order, order_items)
-
-
1
response, response_code = send_request(create_b2c_order_api, request_body, http_method)
-
-
1
handle_response(response, response_code)
-
else
-
1
handle_response({ message: 'No byezzy products ordered' }, 404)
-
end
-
end
-
-
1
def event_grn_status_update_in_wms
-
2
process_wms_event(params)
-
end
-
-
1
def event_consignment_status_update_in_wms
-
1
process_wms_event(params)
-
end
-
-
1
def event_b2c_shipment_status_update_in_wms
-
1
process_wms_event(params)
-
end
-
-
1
def b2c_order_index
-
2
per_page = params[:per_page].presence&.to_i || 10
-
2
page_number = params[:page].presence&.to_i || 1
-
2
filter_created_by = params[:filter_created_by].presence
-
2
http_method = 'GET'
-
-
2
query_params = "page[number]=#{page_number}&page[size]=#{per_page}&filter[created_at]=#{filter_created_by}"
-
-
2
b2c_order_index_api = "https://uatapi.anchanto.com/rest/v1/b2c/orders?#{query_params}"
-
-
2
response, response_code = send_request(b2c_order_index_api, {}, http_method)
-
-
2
if response_code.to_i == 200
-
1
orders = filter_orders_by_seller(@json_response['data'], @seller)
-
1
render json: {
-
orders: orders,
-
meta: @json_response['meta']
-
}, status: :ok
-
else
-
1
render json: response, status: response_code
-
end
-
end
-
-
1
def b2c_order_show
-
2
order_number = params[:order_number]
-
-
2
http_method = 'GET'
-
-
2
b2c_order_show_api = "https://uatapi.anchanto.com/rest/v1/b2c/orders/#{order_number}/details"
-
-
2
response, response_code = send_request(b2c_order_show_api, {}, http_method)
-
-
2
if response_code.to_i == 200
-
1
orders = filter_orders_by_seller([@json_response['data']], @seller)
-
1
render json: {
-
orders: orders,
-
meta: @json_response['meta']
-
}, status: :ok
-
else
-
1
render json: response, status: response_code
-
end
-
end
-
-
1
private
-
-
1
def check_seller
-
11
@seller = @current_user if @current_user.user_type == 'seller'
-
11
render json: { message: 'Invalid seller' }, status: :unprocessable_entity unless @seller
-
end
-
-
1
def find_catalogue
-
7
@catalogue = BxBlockCatalogue::Catalogue.find_by(id: params[:catalogue_id])
-
7
render json: { message: 'Catalogue not found' }, status: :unprocessable_entity unless @catalogue
-
end
-
-
1
def find_order
-
3
@order = BxBlockShoppingCart::Order.find_by(id: params[:order_id])
-
3
render json: { message: 'Order not found' }, status: :unprocessable_entity unless @order
-
end
-
-
1
def validate_params
-
6
return if params[:authorization].present? && @seller
-
-
1
render json: { message: 'Missing required params' }, status: :unprocessable_entity
-
end
-
-
1
def send_request(url, request_body, http_method)
-
9
response, response_code = request_response_body(params[:authorization], url, request_body, http_method)
-
@json_response = begin
-
9
JSON.parse(response)
-
rescue StandardError
-
{}
-
end
-
9
[response, response_code]
-
end
-
-
1
def request_response_body(authorization, request_url, request_body, http_method)
-
9
url = URI(request_url)
-
-
9
https = Net::HTTP.new(url.host, url.port)
-
9
https.use_ssl = true
-
-
9
request = if http_method == 'POST'
-
5
Net::HTTP::Post.new(url)
-
else
-
4
Net::HTTP::Get.new(url)
-
end
-
9
request['Authorization'] =
-
authorization || 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMDAyLCJ3X2NvZGUiOiJCRVpZIiwiZXhwIjoxNzYzMjE2ODQ0fQ.Gp1KqS4Jg5bzv8jbc8bs1fChxpwACK5oOrjRPQXiQN8'
-
9
request['warehouse-code'] = ENV['WMS_WAREHOUSE_CODE']
-
9
request['Content-Type'] = 'application/json'
-
9
request.body = JSON.dump(request_body)
-
-
9
response = https.request(request)
-
9
[response.read_body, response.code]
-
end
-
-
1
def handle_response(response, response_code)
-
6
if response_code.to_i == 200 && update_wms_warehouse
-
create_warehouse_catalogue if @catalogue.present? && @warehouse.present?
-
-
render json: @json_response.merge(
-
catalogue: BxBlockCatalogue::CatalogueSerializer.new(@catalogue),
-
order: BxBlockShoppingCart::OrderSerializer.new(@order)
-
), status: :ok
-
else
-
6
render json: response, status: response_code
-
end
-
end
-
-
1
def update_wms_warehouse
-
wms_attrs = {
-
3
warehouse_type: 'anchanto',
-
warehouse_name: ENV['WMS_WAREHOUSE_NAME'],
-
warehouse_address_1: ENV['WMS_WAREHOUSE_ADDRESS'],
-
warehouse_code: ENV['WMS_WAREHOUSE_CODE'],
-
contact_number: ENV['WMS_WAREHOUSE_CONTACT'],
-
contact_person: '',
-
processing_days: 1
-
}
-
3
@warehouse = BxBlockCatalogue::Warehouse.find_or_initialize_by(warehouse_code: wms_attrs[:warehouse_code])
-
3
@warehouse.assign_attributes(wms_attrs.merge(account_id: @seller&.id))
-
3
@warehouse.save
-
end
-
-
1
def create_warehouse_catalogue
-
variant_group = @catalogue.product_variant_group
-
variant_group_id = variant_group&.id
-
record = BxBlockCatalogue::WarehouseCatalogue.find_or_initialize_by(
-
warehouse_id: @warehouse.id,
-
catalogue_id: @catalogue.id,
-
product_variant_group_id: variant_group_id
-
)
-
record.stocks = @catalogue.stocks
-
record.save!
-
end
-
-
1
def b2c_order_details(order, order_items)
-
1
final_price, total_discount = calculate_final_price(order_items)
-
-
{
-
1
"b2c_order": {
-
"company_code": ENV['WMS_SUPPLIER_CODE'],
-
"shipping_type": 'Purchase Order',
-
"number": order.order_number,
-
"currency_code": 'AED',
-
"carrier": {
-
"carrier_code": ENV['WMS_CARRIER_CODE'],
-
"carrier_name": ENV['WMS_CARRIER_NAME']
-
},
-
"adjustment_attributes": {
-
"total_paid": final_price,
-
"discount": total_discount
-
},
-
"order_items_attributes": order_items_details(order_items),
-
"billing_address_attributes": shipping_billing_address(order),
-
"shipping_address_attributes": shipping_billing_address(order)
-
}
-
}
-
end
-
-
1
def calculate_final_price(order_items)
-
1
total_price = calculate_total_price(order_items)
-
1
total_discount_price = calculate_total_discount(order_items)
-
-
1
[total_discount_price.to_f, (total_discount_price - total_price).to_f.round(2)]
-
end
-
-
1
def calculate_total_price(order_items)
-
1
order_items.map do |item|
-
1
(item&.catalogue&.product_content&.retail_price&.to_f || 0) * item.quantity
-
end.sum.round(2)
-
end
-
-
1
def calculate_total_discount(order_items)
-
2
order_items.sum { |item| item.assign_discount_to_order }
-
end
-
-
1
def order_items_details(order_items)
-
1
order_items.map do |order_item|
-
{
-
1
"unit_price": order_item.price,
-
"retail_price": order_item.catalogue&.product_content&.retail_price,
-
1
"selling_price": (order_item.price * order_item.quantity),
-
"quantity": order_item.quantity,
-
1
"sku": order_item.catalogue&.is_variant ? order_item.catalogue&.product_variant_group&.product_bibc : order_item.catalogue&.bibc
-
}
-
end
-
end
-
-
1
def shipping_billing_address(order)
-
2
shipping_address = order.shipping_address
-
2
if shipping_address
-
{
-
"first_name": shipping_address.first_name,
-
"last_name": shipping_address.last_name,
-
"address1": shipping_address.address_1,
-
"address2": shipping_address.address_2,
-
"city": shipping_address.city,
-
"zipcode": shipping_address.zip_code,
-
"country_iso": 'AE',
-
"state_abbreviation": 'AE',
-
"phone": shipping_address.phone_number
-
}
-
else
-
2
{}
-
end
-
end
-
-
1
def consignment_details(product, quantity)
-
{
-
2
"consignment": {
-
"supplier_code": ENV['WMS_SUPPLIER_CODE'],
-
2
"ship_date": (Date.today + 2.days),
-
2
"receiving_date": (Date.today + 4.days),
-
"consignment_items_attributes": [
-
{
-
"unit_price": product.product_content&.retail_price,
-
"quantity": quantity,
-
2
"sku": product.is_variant ? product&.product_variant_group&.product_bibc : product.bibc
-
}
-
]
-
}
-
}
-
end
-
-
1
def product_details(product)
-
2
product_content = product&.product_content
-
2
shipping_detail = product_content&.shipping_detail
-
2
size_and_capacity = product_content&.size_and_capacity
-
-
{
-
2
"product": {
-
"name": product.product_title,
-
2
"sku": product.is_variant ? product&.product_variant_group&.product_bibc : product.bibc,
-
"storage_type": 'standard',
-
"low_threshold": 20,
-
"buffer_stock": 10,
-
"product_sales_informations_attributes": [{
-
"currency_code": 'AED',
-
2
"cost_price": product_content ? product_content.retail_price : 0.0
-
}],
-
"product_dimensions_attributes": [{
-
"length_cm": shipping_detail&.shipping_length || 0,
-
"width_cm": shipping_detail&.shipping_width || 0,
-
"height_cm": shipping_detail&.shipping_height || 0,
-
"weight_gm": shipping_detail&.shipping_weight || 0,
-
"no_of_units": size_and_capacity&.number_of_pieces || 0
-
}],
-
"product_localizations_attributes": [{
-
"country_iso": 'AE',
-
"name": product.product_title
-
}],
-
"product_hs_attributes": [{
-
"hs_code": size_and_capacity&.hs_code
-
}]
-
}
-
}
-
end
-
-
1
def save_product_response
-
1
product_dimensions_info_hash = @json_response.dig('data', 1, 'product_dimensions_info')
-
1
product_dimensions_key = product_dimensions_info_hash.keys.first if product_dimensions_info_hash
-
1
product_information_value = product_dimensions_info_hash.values.first if product_dimensions_info_hash
-
-
1
WmsProductInfo.create(
-
seller: @seller,
-
catalogue: @catalogue,
-
product_information_id: product_information_value,
-
product_dimensions_info: product_dimensions_key
-
)
-
end
-
-
1
def save_consignment_response
-
1
order_number = @json_response.dig('order_number')
-
-
1
WmsConsignmentOrder.create(
-
seller: @seller,
-
catalogue: @catalogue,
-
order_number: order_number,
-
quantity: @quantity,
-
unit_price: @catalogue&.product_content&.retail_price
-
)
-
end
-
-
1
def successful_response?
-
5
@json_response.present? && @json_response['response'] == 'success'
-
end
-
-
1
def process_wms_event(event_params)
-
4
if request.get?
-
return render json: {message: "Anchanto WMS endpoint ready."}
-
end
-
4
unless event_params["event_parameters"].present?
-
return render json: {message: "missing event parameters"}
-
end
-
-
4
return if event_params.blank?
-
-
8
product_skus = event_params[:products].map { |product| product[:sku] }
-
4
@products = BxBlockCatalogue::Catalogue.where(bibc: product_skus)
-
-
4
@sellers = @products.map(&:seller).uniq
-
-
4
if @sellers.present?
-
4
@wms_response = event_params
-
4
create_wms_event_update_and_notify_sellers
-
4
render json: @wms_response, status: :ok
-
else
-
render json: { error: 'Seller not found' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def filter_orders_by_seller(orders_data, seller)
-
2
orders_data.map do |order|
-
2
filtered_items = filter_order_items_by_seller(order['attributes']['order_items'], seller)
-
2
next if filtered_items.empty?
-
-
1
order['attributes']['order_items'] = filtered_items
-
2
order['attributes']['order_total'] = filtered_items.sum { |item| item['paid_price'].to_f }.round(2)
-
1
order['attributes']
-
end.compact
-
end
-
-
1
def filter_order_items_by_seller(order_items, seller)
-
2
order_items.select do |item|
-
2
catalogue = BxBlockCatalogue::Catalogue.find_by(bibc: item['sku'])
-
2
catalogue&.seller == seller
-
end
-
end
-
-
1
def create_wms_event_update_and_notify_sellers
-
4
return unless @wms_response && @sellers
-
-
4
@sellers.each do |seller|
-
4
WmsEventUpdate.create(
-
warehouse_code: @wms_response.dig(:event_parameters, :warehouse_code),
-
consignment_type: @wms_response.dig(:event, :consignment_type),
-
shipment_number: @wms_response.dig(:event, :shipment_number),
-
po_number: @wms_response.dig(:event, :po_number),
-
old_state: @wms_response.dig(:event, :old_state),
-
new_state: @wms_response.dig(:event, :new_state),
-
event_on: @wms_response.dig(:event, :event_on),
-
time_zone: @wms_response.dig(:event, :time_zone),
-
seller_email: seller.email,
-
products: @wms_response[:products]
-
)
-
-
4
notify_seller_of_update(seller, @wms_response)
-
end
-
end
-
-
1
def notify_seller_of_update(seller, wms_event)
-
4
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: seller, subject: 'WMS Event Update', file: 'wms_event_notification', wms_event: wms_event)
-
.notification.deliver_now
-
end
-
end
-
end
-
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token
-
1
before_action :get_user
-
-
1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
1
private
-
-
1
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
1
def get_user
-
34
@current_user = AccountBlock::Account.find(@token.id)
-
end
-
-
1
def format_activerecord_errors(errors)
-
4
result = []
-
4
errors.each do |attribute, error|
-
10
attribute_name = attribute.to_s.gsub('_', ' ')
-
10
result << "#{attribute_name.capitalize} #{error}"
-
end
-
4
result
-
end
-
end
-
end
-
# rubocop:enable Naming/AccessorMethodName
-
1
module BxBlockOrderManagement
-
1
class DeliveryRequestsController < ApplicationController
-
1
before_action :find_seller, only: [:index, :create, :update, :destroy]
-
1
before_action :set_delivery_request, only: [:update, :destroy, :show]
-
-
-
1
def index
-
1
@delivery_requests = @seller.delivery_requests.order(created_at: :desc)
-
1
unless @delivery_requests.present?
-
1
render json: {
-
message: "No Delivery Request is present"
-
} and return
-
end
-
render json: BxBlockOrderManagement::DeliveryRequestSerializer.new(
-
@delivery_requests, meta: {message: "List of all delivery request"}
-
).serializable_hash
-
end
-
-
1
def create
-
2
find_order(params[:data][:attributes][:order_number])
-
2
@delivery_request = DeliveryRequest.new(delivery_request_params.merge({seller_id: @seller.id, order_id: @order&.id}))
-
2
if @delivery_request.save
-
1
render json: BxBlockOrderManagement::DeliveryRequestSerializer.new(@delivery_request, meta: {
-
message: "Delivery Request Created Successfully"
-
}).serializable_hash, status: :created
-
else
-
1
render json: {errors: format_activerecord_errors(@delivery_request.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
find_order(@delivery_request.order_number)
-
2
if @delivery_request.update(delivery_request_params.merge({seller_id: @seller.id, order_id: @order&.id}))
-
1
render json: BxBlockOrderManagement::DeliveryRequestSerializer.new(@delivery_request, meta: {
-
message: "Delivery request Updated Successfully"
-
}).serializable_hash, status: :ok
-
else
-
1
render json: {errors: format_activerecord_errors(@delivery_request.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @delivery_request.destroy
-
1
render json: {message: "Delivery request deleted succesfully!"}, status: :ok
-
end
-
end
-
-
1
def show
-
1
if @delivery_request.present?
-
1
render json: BxBlockOrderManagement::DeliveryRequestSerializer.new(@delivery_request, meta: {
-
message: "Delivery request fetched Successfully"
-
}).serializable_hash, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def delivery_request_params
-
4
params.require(:data).require(:attributes).permit(
-
:warehouse_id, :warehouse_name, :seller_id, :order_number, :address_1, :address_2, :status
-
)
-
end
-
-
1
def set_delivery_request
-
4
@delivery_request = DeliveryRequest.find_by(id: params[:id])
-
4
if @delivery_request.nil?
-
render json: {
-
message: "Delivery request with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def find_seller
-
6
@seller = AccountBlock::Account.find_by(id: @token.id, user_type: 'seller')
-
6
render json: {errors: 'Seller is invalid'} and return unless @seller
-
end
-
-
1
def find_order(order_number)
-
4
@order = BxBlockShoppingCart::Order.find_by(order_number: order_number)
-
4
@order
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class OrderStatuesController < ApplicationController
-
1
before_action :set_order_status, only: [:show]
-
-
1
def index
-
1
render json: OrderStatusSerializer.new(OrderStatus.all).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: OrderStatusSerializer.new(@order_status).serializable_hash, status: :ok
-
end
-
-
1
private
-
-
1
def set_order_status
-
1
@order_status = OrderStatus.find_by(id: params[:id])
-
1
if @order_status.nil?
-
render json: {
-
message: "Order status with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class StockIntakesController < ApplicationController
-
1
before_action :find_seller, only: [:index, :create, :update, :destroy]
-
1
before_action :set_stock_intake, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@stock_intakes = StockIntake.all.where(seller: @seller).order(created_at: :desc)
-
-
1
render json: StockIntakeSerializer.new(@stock_intakes).serializable_hash
-
end
-
-
1
def show
-
1
render json: StockIntakeSerializer.new(@stock_intake).serializable_hash
-
end
-
-
1
def create
-
3
@stock_intake = StockIntake.new(stock_intake_params.merge(seller: @seller))
-
-
3
if @stock_intake.save
-
2
render json: StockIntakeSerializer.new(@stock_intake).serializable_hash, status: :created
-
else
-
1
render json: {errors: format_activerecord_errors(@stock_intake.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
3
if @stock_intake.update(stock_intake_params)
-
2
render json: StockIntakeSerializer.new(@stock_intake).serializable_hash
-
else
-
1
render json: {errors: format_activerecord_errors(@stock_intake.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @stock_intake.destroy
-
1
render json: {message: "Stock intake deleted succesfully!"}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_stock_intake
-
5
@stock_intake = StockIntake.find(params[:id])
-
end
-
-
1
def stock_intake_params
-
6
params.require(:stock_intake).permit(:catalogue_id, :stock_value, :stock_qty, :ship_date, :receiving_date)
-
end
-
-
1
def find_seller
-
8
@seller = AccountBlock::Account.find_by(id: @token.id, user_type: 'seller')
-
8
render json: {errors: 'Seller is invalid'} and return unless @seller
-
end
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class ProductViewsController < ApplicationController
-
1
skip_before_action :validate_json_web_token, only: [:create]
-
1
before_action :find_user, only: [:browsing_history]
-
-
1
def create
-
2
@view = ProductView.new(product_view_params)
-
-
2
if @view.save
-
1
render json: { success: true, view: @view }, status: :created
-
else
-
1
render json: { errors: @view.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def browsing_history
-
-
2
browsing_histories = ProductView
-
.includes(:catalogue)
-
.where(user: @account, catalogues: { status: true })
-
.where('viewed_at >= ?', 15.days.ago)
-
.order(viewed_at: :desc)
-
-
4
browsing_histories = browsing_histories.uniq { |view| view.catalogue_id }
-
-
-
2
render json: BxBlockSalesreporting::ProductViewSerializer.new(browsing_histories), status: :ok
-
end
-
-
1
private
-
-
1
def find_user
-
3
@account = AccountBlock::Account.find_by(id: @token&.id, user_type: 'buyer')
-
3
render json: { errors: 'Buyer is invalid' } and return unless @account
-
end
-
-
1
def product_view_params
-
2
params.require(:product_view).permit(:catalogue_id, :user_id)
-
end
-
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class ReportsController < ApplicationController
-
1
before_action :current_seller, only: [:sales_performance]
-
-
1
def sales_performance
-
13
return render json: {errors: "Report type is required"}, status: :bad_request if params[:report_type].blank?
-
-
12
report_type = params[:report_type]
-
12
seller = @current_seller
-
12
page = params[:page].to_i > 0 ? params[:page].to_i : 1
-
12
per_page = params[:per_page].to_i > 0 ? params[:per_page].to_i : 10
-
-
12
sort_by = params[:sort_by]
-
12
sort_order = params[:sort_order] || 'asc'
-
-
12
if report_type == 'compare_sales'
-
2
report = SalesReportService.new(nil, nil, report_type, seller).call
-
else
-
10
report = fetch_sales_report_with_dates(report_type, seller, sort_by, sort_order)
-
10
return if performed?
-
end
-
-
11
if params[:export_csv]&.to_s == 'true'
-
5
return export_sales_report(report, report_type) unless report.empty?
-
1
return render json: { errors: "No report data available for export" }, status: :unprocessable_entity
-
end
-
-
6
total_count = report.count
-
6
report = paginate_array(report, page, per_page)
-
-
6
render json: { results: report, total_count: total_count}, status: :ok
-
end
-
-
1
def fetch_sales_report_with_dates(report_type, seller, sort_by, sort_order)
-
10
if params[:start_date].blank? || params[:end_date].blank?
-
1
return render json: { errors: "Please provide start_date and end_date" }, status: :bad_request
-
end
-
-
9
start_date = params[:start_date].to_date
-
9
end_date = params[:end_date].to_date
-
-
9
report = SalesReportService.new(start_date, end_date, report_type, seller, sort_by, sort_order).call
-
-
9
report
-
end
-
-
1
def export_sales_report(report, report_type)
-
4
headers = if report_type == "compare_sales"
-
6
report.values.first.keys.map { |key| key.to_s.titleize }.unshift("Period")
-
else
-
36
report.first.keys.map { |key| key.to_s.titleize }
-
end
-
-
11
periods = (report_type == "compare_sales" ? report.keys.map { |key| key.to_s.titleize } : [] )
-
-
4
formatted_data = headers.each_with_object({}) do |header, hash|
-
39
hash[header] = []
-
end
-
-
4
if report_type == 'compare_sales'
-
1
formatted_data['Period'] = periods
-
-
1
report.each do |period, data|
-
7
data.each do |key, value|
-
35
formatted_data[key.to_s.titleize] << value
-
end
-
end
-
else
-
3
report.each do |data_row|
-
3
headers.each do |header|
-
33
converted_key = header.downcase.gsub(' ','_').to_sym
-
33
formatted_data[header] << data_row[converted_key]
-
end
-
end
-
end
-
-
4
render json: { headers: headers, values: formatted_data }
-
end
-
-
1
private
-
-
1
def current_seller
-
13
@current_seller = AccountBlock::Account.find_by(id: @token&.id, user_type: "seller")
-
13
render json: {error: "Seller not found"} and return unless @current_seller
-
end
-
-
1
def paginate_array(array, page, per_page)
-
return Kaminari.paginate_array(array)
-
6
.page(page).per(per_page) if array.is_a?(Array)
-
-
2
array
-
end
-
-
end
-
end
-
1
module BxBlockSeoSetting
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
# serialization_scope :view_context
-
-
1
private
-
-
1
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
1
module BxBlockSeoSetting
-
1
class SeoSettingsController < ApplicationController
-
1
before_action :set_seo_setting, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@seo_settings = SeoSetting.all.order(created_at: :desc)
-
1
if @seo_settings.present?
-
1
render json: SeoSettingSerializer.new(@seo_settings, meta: { message: "Successfully Loaded" }).serializable_hash, status: :ok
-
else
-
render json: { message: "No SEO settings found" }, status: :not_found
-
end
-
end
-
-
1
def show
-
1
render json: SeoSettingSerializer.new(@seo_setting).serializable_hash, status: :ok
-
end
-
-
1
def create
-
4
@seo_setting = SeoSetting.new(seo_setting_params)
-
4
if @seo_setting.save
-
2
render json: SeoSettingSerializer.new(@seo_setting).serializable_hash, status: :created
-
else
-
2
render json: @seo_setting.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @seo_setting.update(seo_setting_params)
-
1
render json: SeoSettingSerializer.new(@seo_setting).serializable_hash, status: :ok
-
else
-
1
render json: @seo_setting.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @seo_setting&.destroy
-
1
render json:{ meta: { message: "seo setting Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
1
private
-
1
def set_seo_setting
-
4
@seo_setting = SeoSetting.find(params[:id])
-
end
-
-
1
def seo_setting_params
-
6
jsonapi_deserialize(params)
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
1
def format_activerecord_errors(errors)
-
1
result = []
-
1
errors.each do |attribute, error|
-
attribute_name = attribute.to_s.gsub('_', ' ')
-
result << "#{attribute_name.capitalize} #{error}"
-
end
-
1
result
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class OrderItemsController < ApplicationController
-
1
include BxBlockShoppingCart::OrderConcern
-
-
1
before_action :get_user, only: [:create, :destroy, :guest_user_order]
-
1
before_action :find_or_build_order, only: [:create, :destroy, :guest_user_order]
-
1
before_action :find_order_item, only: [:destroy]
-
1
before_action :find_individual_order_item, only: [:update]
-
1
before_action :find_order_status, only: [:update]
-
1
before_action :get_seller, only: [:index]
-
# before_action :get_service_provider, only: %i(get_booked_time_slots)
-
-
1
def index
-
7
per_page = params[:per_page].presence&.to_i || 10
-
7
page_number = params[:page].presence&.to_i || 1
-
-
7
orders = Order.all.includes(:order_status)
-
.joins(order_items: { catalogue: [:seller, :product_content]})
-
.where('accounts.id': @seller.id).order(order_placed_at: :desc)
-
-
7
order_items = orders.flat_map do |order|
-
14
order.order_items.select do |item|
-
14
item.order_status&.status&.in?(params[:filter_by].map(&:downcase).map(&:parameterize).map(&:underscore)) &&
-
item.catalogue.seller_id == @seller.id
-
end
-
end.uniq
-
-
7
filtered_order_item_ids = order_items.map(&:id).uniq
-
-
7
if params[:search_query].present?
-
1
search_query = params[:search_query].downcase
-
1
filtered_order_item_ids = order_items.select do |item|
-
1
item.catalogue.sku.downcase.include?(search_query) ||
-
item.order.order_number.downcase.include?(search_query)
-
end.map(&:id).uniq
-
end
-
-
7
order_items = OrderItem.where(id: filtered_order_item_ids)
-
7
total_count = order_items.count
-
-
7
case params[:sort_by]
-
when 'date_oldest'
-
1
order_items = order_items.order(updated_at: :asc)
-
when 'product_name_AZ'
-
1
order_items = order_items.joins(catalogue: :product_content).order('product_contents.product_title ASC')
-
when 'product_name_ZA'
-
1
order_items = order_items.joins(catalogue: :product_content).order('product_contents.product_title DESC')
-
else
-
4
order_items = order_items.order(updated_at: :desc)
-
end
-
-
7
if order_items.present?
-
6
order_items = order_items.page(page_number).per(per_page)
-
end
-
-
7
render json: {total_count: total_count, orders: custom_order_items_response(order_items)}
-
end
-
-
1
def create
-
5
@order_item = find_or_build_order_item(params[:order_items][:catalogue_id])
-
-
5
if @order_item.present? && params[:order_items][:shopping_cart]
-
2
@order_item.update(order_items_params)
-
3
elsif @order_item
-
1
@order_item.quantity += order_items_params.delete(:quantity).to_i
-
1
@order_item.update(order_items_params.except(:quantity,:shopping_cart))
-
else
-
2
@order_item = @order.order_items.create(order_items_params)
-
end
-
5
if @order_item.errors.present?
-
1
render json: {
-
errors: @order_item.errors
-
}, status: :unprocessable_entity
-
else
-
4
@order.reload
-
4
render json: BxBlockShoppingCart::OrderSerializer.new(@order).serializable_hash, status: 201
-
end
-
end
-
-
1
def update
-
5
if @order_item.update(order_status: @order_status)
-
5
render json: OrderItemSerializer.new(@order_item).serializable_hash , status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(@order_item.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def guest_user_order
-
4
if params[:order_items].present?
-
3
params[:order_items].each do |order_item_params|
-
3
permitted_params = order_item_params.permit(:catalogue_id, :product_variant_group_id, :quantity)
-
3
@order_item = find_or_build_order_item(permitted_params[:catalogue_id])
-
-
3
catalogue = BxBlockCatalogue::Catalogue.find_by(id: permitted_params[:catalogue_id])
-
3
available_stock = catalogue&.stocks || 0
-
-
3
requested_quantity = @order_item ? @order_item.quantity + permitted_params[:quantity].to_i : permitted_params[:quantity].to_i
-
3
final_quantity = [requested_quantity, available_stock].min
-
-
3
if @order_item
-
2
@order_item.update(quantity: final_quantity)
-
else
-
1
permitted_params[:quantity] = final_quantity
-
1
@order_item = @order.order_items.create(permitted_params)
-
end
-
end
-
-
3
@order.reload
-
3
render json: {
-
message: 'Order items added successfully',
-
order: BxBlockShoppingCart::OrderSerializer.new(@order).serializable_hash
-
}, status: :created
-
else
-
1
render json: {
-
message: 'Provide valid products'
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
2
if @order_item.destroy
-
1
@order.reload
-
1
render json: {message: "Order items deleted successfully!"}, status: :ok
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@order_item.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def order_items_params
-
6
params.require(:order_items).permit(
-
:catalogue_id, :quantity, :taxable, :order_status_id,
-
:taxable_value, :other_charges, :product_variant_group_id
-
)
-
end
-
-
1
def get_user
-
12
@customer = AccountBlock::Account.find(@token.id)
-
12
render json: {errors: 'Customer is invalid'} and return unless @customer.present?
-
end
-
-
1
def find_or_build_order
-
12
@order = @customer.orders.includes(:order_status).where(order_statuses: { status: ["on_going", "scheduled"] }).last
-
12
@order ||= Order.create(customer_id: @customer.id)
-
end
-
-
1
def find_order_item
-
3
@order_item = @order.order_items.find(params[:id])
-
end
-
-
1
def find_or_build_order_item(catalogue_id)
-
8
@order.order_items.find_by(catalogue_id: catalogue_id)
-
end
-
-
1
def find_order_status
-
6
@order_status = BxBlockOrderManagement::OrderStatus.find_by(id: params[:order_status_id])
-
6
if @order_status.nil?
-
1
render json: {
-
message: "Order status not found"
-
}, status: :not_found
-
end
-
end
-
-
1
def find_individual_order_item
-
6
@order_item = OrderItem.find(params[:id])
-
end
-
-
1
def get_seller
-
7
@seller = AccountBlock::Account.find_by(id: @token.id, user_type: 'seller')
-
7
render json: {errors: 'seller is invalid'} and return unless @seller.present?
-
end
-
-
1
def custom_order_items_response(order_items)
-
7
return { message: 'No return orders' } unless order_items.present?
-
-
6
order_items.map do |order_item|
-
{
-
6
order_details: {
-
id: order_item.order.id,
-
order_number: order_item.order.order_number,
-
total_fees: order_item.order.total_fees,
-
total_items: order_item.order.total_items,
-
discount: order_item.order.discount,
-
total_tax: order_item.order.total_tax,
-
final_price: order_item.order.final_price,
-
order_placed_at: order_item.order.order_placed_at,
-
delivered_at: order_item.order.delivered_at,
-
time_passed_since_order_placed: time_passed_since_creation(order_item.order.order_placed_at),
-
time_passed_since_delivered: time_passed_since_creation(order_item.order.delivered_at),
-
accepted: order_item.order.accepted,
-
order_status: BxBlockOrderManagement::OrderStatusSerializer.new(order_item.order.order_status),
-
customer: AccountBlock::AccountSerializer.new(order_item.order.customer),
-
seller: AccountBlock::AccountSerializer.new(@seller),
-
order_item_details: {
-
id: order_item.id,
-
price: order_item.price,
-
quantity: order_item.quantity,
-
taxable: order_item.taxable,
-
taxable_value: order_item.taxable_value,
-
order_status: BxBlockOrderManagement::OrderStatusSerializer.new(order_item.order_status),
-
catalogue: BxBlockCatalogue::CatalogueSerializer.new(order_item.catalogue),
-
6
selected_product_variant: order_item.product_variant_group.present? ? {
-
id: order_item.product_variant_group.id,
-
product_sku: order_item.product_variant_group.product_sku,
-
product_besku: order_item.product_variant_group.product_besku,
-
group_attributes: order_item.product_variant_group.group_attributes&.group_by(&:attribute_name).map do |attribute_name, groups|
-
{
-
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
} : nil,
-
},
-
shipping_address: get_delivery_address(order_item.order),
-
coupon_code: BxBlockCouponCg::CouponCodeSerializer.new(order_item.order.coupon_code),
-
6
return_reason_details: order_item.return_reason_details.map {|rrd| rrd.serializable_hash},
-
1
return_exchange_requests: order_item.return_exchange_requests.map {|rer| rer.serializable_hash}
-
}
-
}
-
end
-
end
-
-
1
def time_passed_since_creation(created_at)
-
12
return 'N/A' unless created_at.present?
-
-
6
distance_of_time_in_words(created_at, Time.now)
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class OrdersController < ApplicationController
-
1
include BxBlockShoppingCart::OrderConcern
-
-
1
before_action :get_user, only: %i[index show create index apply_coupon_to_order]
-
1
before_action :find_order, only: %i[show apply_coupon_to_order]
-
-
1
before_action :find_seller, only: %i[seller_orders show_seller_order]
-
-
1
def index
-
5
per_page = params[:per_page].presence&.to_i || 10
-
5
page_number = params[:page].presence&.to_i || 1
-
5
total_count = 0
-
5
orders = @customer.orders.includes(:order_status)
-
5
filtered_orders = filter_orders(params, orders).order(order_placed_at: :desc)
-
-
5
if params[:order_item_status].present?
-
1
total_count = BxBlockShoppingCart::OrderItem.includes(:order_status)
-
.where(order: filtered_orders)
-
.where(order_statuses: { status: params[:order_item_status].map(&:downcase).map(&:parameterize).map(&:underscore) })
-
.count
-
else
-
4
total_count = filtered_orders.includes(:order_items).count('shopping_cart_order_items.id')
-
end
-
-
5
filtered_orders = filtered_orders.page(page_number).per(per_page) if filtered_orders.present?
-
-
5
orders_json = custom_order_response(filtered_orders, params[:order_item_status] || [])
-
-
5
render json: { orders: orders_json, total_count: total_count }
-
end
-
-
1
def seller_orders
-
7
per_page = params[:per_page].presence&.to_i || 10
-
7
page_number = params[:page].presence&.to_i || 1
-
-
7
params[:fulfilled_by]
-
-
7
orders = Order.all.includes(:order_status)
-
.joins(order_items: { catalogue: %i[seller product_content] })
-
.where('accounts.id': @seller.id).where.not(order_statuses: { name: 'Return' })
-
7
seller_filtered_orders = filter_orders(params, orders)
-
7
total_count = seller_filtered_orders.count
-
7
order_items = seller_filtered_orders.flat_map do |order|
-
# order.order_items.select { |item| @seller.catalogues.map(&:id).include?(item.catalogue_id) }
-
12
filter_seller_order_items(order, params[:fulfilled_by]).map do |item|
-
12
filter_by = Array(params[:filter_by])
-
12
if filter_by.present? && !filter_by.include?(item&.order_status&.status.to_s)
-
next
-
end
-
{
-
12
order: order,
-
order_item: item,
-
catalogue: item.catalogue
-
}
-
end
-
end
-
7
case params[:sort_by]
-
when 'date_latest'
-
1
sorted_orders = seller_filtered_orders.order(order_placed_at: :desc)
-
when 'date_oldest'
-
1
sorted_orders = seller_filtered_orders.order(order_placed_at: :asc)
-
when 'product_name_AZ'
-
1
sorted_orders = seller_filtered_orders.order('product_contents.product_title ASC')
-
1
order_items = order_items.sort_by do |item|
-
2
item[:order_item].catalogue&.product_content&.product_title
-
end
-
when 'product_name_ZA'
-
1
sorted_orders = seller_filtered_orders.order('product_contents.product_title DESC')
-
3
order_items = order_items.sort_by { |item| item[:order_item].catalogue&.product_content&.product_title }.reverse
-
else
-
3
sorted_orders = seller_filtered_orders.order(order_placed_at: :desc)
-
# order_items = order_items.sort_by { |obj| obj[:order].order_placed_at || Time.at(0).reverse }
-
end
-
-
7
if params[:search_query].present?
-
1
search_query = params[:search_query].downcase
-
1
sorted_orders = sorted_orders.where('lower(catalogues.sku) LIKE :query OR lower(order_number) LIKE :query',
-
query: "%#{search_query}%")
-
1
total_count = sorted_orders.count
-
end
-
-
7
paginated_orders = sorted_orders.page(page_number).per(per_page)
-
7
render json: { message: 'No order present ', total_count: 0 } and return unless paginated_orders.present?
-
-
6
render json: render_show_seller_order(paginated_orders, order_items, total_count)
-
end
-
-
1
def show_seller_order
-
1
order = Order.includes(:order_status)
-
.joins(order_items: { catalogue: :seller })
-
.find_by('accounts.id': @seller.id, id: params[:id])
-
-
1
render json: { message: 'Order not found' } and return unless order.present?
-
-
-
2
order_items = order.order_items.select { |item| @seller.catalogues.map(&:id).include?(item.catalogue_id) }
-
1
all_order_items = order_items.map do |item|
-
1
{ order: order, order_item: item, catalogue: item.catalogue }
-
end
-
-
1
render json: render_show_seller_order([order], all_order_items, nil)
-
end
-
-
1
def apply_coupon_to_order
-
2
coupon_code = BxBlockCouponCg::CouponCode.find_by(code: params[:coupon_code])
-
2
if coupon_code && @order.coupon_code.blank?
-
1
update_discount_to_order(@order, coupon_code)
-
1
render json: BxBlockShoppingCart::OrderSerializer.new(@order).serializable_hash.merge({ message: 'coupon_code applied' })
-
else
-
1
render json: { errors: 'Invalid coupon code or coupon code not active' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def show
-
4
if %w[on_going scheduled].include?(@order.order_status&.status)
-
4
@order.order_items.each do |order_item|
-
4
order_item.assign_price_to_order_item
-
4
order_item.save
-
end
-
4
@order.reload
-
end
-
4
render json: BxBlockShoppingCart::OrderSerializer.new(@order)
-
end
-
-
1
def update
-
6
order_status_name = order_params.delete(:status)
-
6
order_status = BxBlockOrderManagement::OrderStatus.find_by(status: order_status_name&.downcase)
-
6
order = Order.find_by(id: params[:id])
-
6
order_items = order.order_items.where(id: params[:orders][:order_item_id])
-
6
user = AccountBlock::Account.find_by(id: @token.id)
-
6
render json: { errors: 'User invalid' } and return unless user.present?
-
-
6
order_failed_action = 'Order Status update failed'
-
6
order_failed_message = "Order(id: #{order.order_number}) status failed to update, tried update status to #{order_status_name} by #{user.full_name}"
-
-
6
if order.present? && order_status.present?
-
5
Rails.logger.info "#{order_params}"
-
5
puts order_params
-
5
order.update(order_params.merge(order_status_id: order_status.id))
-
5
if order_items.update(order_status_id: order_status.id, accepted: params[:orders][:accepted])
-
5
order_activity_log(user, 'Order Status updated',
-
"Order(id: #{order.order_number}) status updated to #{order_status_name == 'ordered' ? 'ordered/placed' : order_status_name} by #{user.full_name}")
-
5
render json: BxBlockShoppingCart::OrderSerializer.new(order).serializable_hash
-
else
-
order_activity_log(user, order_failed_action, order_failed_message)
-
render json: {
-
errors: format_activerecord_errors(order.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
1
order_activity_log(user, order_failed_action, order_failed_message)
-
1
render json: { errors: 'Invalid order or order status' }, status: :unprocessable_entity
-
end
-
end
-
-
# // these api only for BE , for deleting purpose in testing datas
-
1
def destroy
-
1
order = Order.find_by(id: params[:id])
-
1
return unless order
-
-
1
order.destroy
-
1
render json: { message: 'order destroyed' }, status: :ok
-
end
-
-
1
def destroy_all_orders
-
2
orders = BxBlockShoppingCart::Order.all
-
-
2
if orders.empty?
-
1
render json: { message: 'No orders present' }, status: :ok
-
else
-
1
orders.destroy_all
-
1
order_items = BxBlockShoppingCart::OrderItem.all
-
# // this deletion added for order items because some order deleted previously but not order items
-
1
order_items.destroy_all if order_items.present?
-
1
render json: { message: 'Destroyed all orders' }, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def order_params
-
21
params.require(:orders).permit(
-
:status, :address_id, :order_status_id, :accepted
-
)
-
end
-
-
1
def get_user
-
11
@customer = AccountBlock::Account.find_by(id: @token.id, user_type: 'buyer')
-
11
render json: { errors: 'Customer is invalid' } and return unless @customer.present?
-
end
-
-
1
def find_seller
-
8
@seller = AccountBlock::Account.find_by(id: @token.id, user_type: 'seller')
-
8
render json: { errors: 'Seller is invalid' } and return unless @seller
-
end
-
-
1
def find_order
-
6
@order = @customer.orders.find(params[:id])
-
end
-
-
1
def calculate_discount(order, coupon_code)
-
1
discount_amount = (order.total_fees * (coupon_code.discount.to_f / 100)).round(2)
-
-
1
[discount_amount, order.total_fees].min
-
end
-
-
1
def update_discount_to_order(order, coupon_code)
-
1
order.coupon_code = coupon_code
-
1
discount = calculate_discount(order, coupon_code) || 0.0
-
1
total_discount = order.discount + discount
-
1
final_price = order.final_price - discount
-
1
order.update(discount: total_discount, final_price: final_price)
-
end
-
-
1
def filter_orders(params, orders)
-
12
if params[:filter_by].present? && params[:filter_by] == 'history'
-
1
orders.completed_cancelled
-
11
elsif params[:filter_by].present? && params[:filter_by].is_a?(Array)
-
2
orders.where('order_statuses.status': params[:filter_by].map(&:downcase).map(&:parameterize).map(&:underscore))
-
9
elsif params[:filter_by].present?
-
2
orders.where('order_statuses.status': params[:filter_by]&.downcase&.parameterize&.underscore)
-
else
-
7
orders
-
end
-
end
-
-
1
def render_show_seller_order(orders, all_order_items, total_count)
-
7
result = all_order_items.compact.map do |entry|
-
13
order = entry[:order]
-
13
order_item = entry[:order_item]
-
13
catalogue = entry[:catalogue]
-
-
{
-
13
order_id: order.id,
-
order_number: order.order_number,
-
status: order.status,
-
total_fees: calculate_total_fees(Array(order_item)),
-
total_items: count_total_items(Array(order_item)),
-
discount: calculate_total_discount(Array(order_item)),
-
total_tax: calculate_total_tax(Array(order_item)),
-
final_price: calculate_final_price(Array(order_item)),
-
ordered_at: order.order_placed_at,
-
delivered_at: order.delivered_at,
-
time_passed_since_order_placed: time_passed_since_creation(order.order_placed_at),
-
time_passed_since_delivered: time_passed_since_creation(order.delivered_at),
-
created_at: order.created_at,
-
updated_at: order.updated_at,
-
accepted: order.accepted,
-
order_status: BxBlockOrderManagement::OrderStatusSerializer.new(order.order_status),
-
customer: AccountBlock::AccountSerializer.new(order.customer),
-
seller: AccountBlock::AccountSerializer.new(@seller),
-
shipping_address: get_delivery_address(order),
-
coupon_code: BxBlockCouponCg::CouponCodeSerializer.new(order.coupon_code),
-
shipped_order_details: order.shipped_order_details.map(&:serializable_hash),
-
-
order_item: {
-
id: order_item.id,
-
catalogue_id: order_item.catalogue_id,
-
price: order_item.price,
-
quantity: order_item.quantity,
-
discount_price: order_item.discount_price,
-
taxable: order_item.taxable,
-
taxable_value: order_item.taxable_value,
-
accepted: order_item.accepted,
-
order_status: BxBlockOrderManagement::OrderStatusSerializer.new(order_item.order_status),
-
item: BxBlockCatalogue::CatalogueSerializer.new(
-
catalogue
-
).serializable_hash[:data]
-
-
}
-
}
-
end
-
20
result = result.sort_by { |r| -(r[:ordered_at]&.to_time.to_i || 0) }
-
7
result.push(total_count).compact
-
end
-
-
1
def render_order_items(order_items)
-
BxBlockShoppingCart::OrderItemSerializer.new(order_items)
-
end
-
-
1
def filter_seller_order_items(order, fulfilled_by)
-
12
if fulfilled_by
-
order.order_items.select do |item|
-
@seller.catalogues.map(&:id).include?(item.catalogue_id) && item.catalogue.fulfilled_type == params[:fulfilled_by]
-
end
-
else
-
24
order.order_items.select { |item| @seller.catalogues.map(&:id).include?(item.catalogue_id) }
-
end
-
end
-
-
1
def calculate_total_fees(order_items)
-
52
order_items.map { |item| item.price * item.quantity }.sum || 0
-
end
-
-
1
def count_total_items(order_items)
-
26
order_items.map { |item| item.quantity }.sum || 0
-
end
-
-
1
def calculate_total_discount(order_items)
-
52
order_items.map { |item| item.discount_price * item.quantity }.sum || 0
-
end
-
-
1
def calculate_final_price(order_items)
-
13
total_fees = if calculate_total_discount(order_items) > 0
-
[calculate_total_fees(order_items), calculate_final_discount_price(order_items)].min
-
else
-
13
calculate_total_fees(order_items) || 0.0
-
end
-
13
total_tax = calculate_total_tax(order_items)
-
-
13
total_fees + total_tax
-
end
-
-
1
def calculate_final_discount_price(order_items)
-
final_discount = 0
-
order_items.each do |item|
-
final_discount += if item.discount_price > 0
-
(item.discount_price * item.quantity)
-
else
-
(item.price * item.quantity)
-
end
-
end
-
final_discount
-
end
-
-
1
def calculate_total_tax(order_items)
-
52
order_items.map { |item| item.quantity * item.taxable_value }.reject(&:blank?).sum
-
end
-
-
1
def time_passed_since_creation(created_at)
-
36
return 'N/A' unless created_at.present?
-
-
21
distance_of_time_in_words(created_at, Time.now)
-
end
-
-
1
def custom_order_response(orders, order_item_status)
-
5
return { message: 'No order present' } unless orders.present?
-
-
5
order_items_collection = []
-
-
5
orders.each do |order|
-
6
order_items = if order_item_status.present?
-
2
order.order_items.includes(:order_status)
-
.where(order_statuses: { status: order_item_status.map(&:downcase).map(&:parameterize).map(&:underscore) })
-
else
-
4
order.order_items
-
end
-
6
order_items.each do |order_item|
-
5
order_items_collection << {
-
order_details: {
-
id: order.id,
-
order_number: order.order_number,
-
total_fees: order.total_fees,
-
total_items: order.total_items,
-
discount: order.discount,
-
total_tax: order.total_tax,
-
final_price: order.final_price,
-
order_placed_at: order.order_placed_at,
-
delivered_at: order.delivered_at,
-
time_passed_since_order_placed: time_passed_since_creation(order.order_placed_at),
-
time_passed_since_delivered: time_passed_since_creation(order.delivered_at),
-
accepted: order.accepted,
-
order_status: BxBlockOrderManagement::OrderStatusSerializer.new(order.order_status),
-
customer: AccountBlock::AccountSerializer.new(order.customer),
-
seller: AccountBlock::AccountSerializer.new(@seller),
-
order_item_details: {
-
id: order_item.id,
-
price: order_item.price,
-
quantity: order_item.quantity,
-
taxable: order_item.taxable,
-
taxable_value: order_item.taxable_value,
-
accepted: order_item.accepted,
-
order_status: BxBlockOrderManagement::OrderStatusSerializer.new(order_item.order_status),
-
catalogue: BxBlockCatalogue::CatalogueSerializer.new(order_item.catalogue),
-
5
selected_product_variant: if order_item.product_variant_group.present?
-
{
-
id: order_item.product_variant_group.id,
-
product_sku: order_item.product_variant_group.product_sku,
-
product_besku: order_item.product_variant_group.product_besku,
-
group_attributes: order_item.product_variant_group.group_attributes&.group_by(&:attribute_name)&.map do |attribute_name, groups|
-
{
-
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
}
-
end
-
},
-
shipping_address: get_delivery_address(order),
-
coupon_code: BxBlockCouponCg::CouponCodeSerializer.new(order.coupon_code),
-
return_reason_details: order_item.return_reason_details.map { |rrd| rrd.serializable_hash },
-
shipped_order_details: order_item.shipped_order_detail,
-
return_exchange_requests: order_item.return_exchange_requests.map { |rer| rer.serializable_hash }
-
}
-
}
-
end
-
end
-
-
5
order_items_collection
-
end
-
-
1
def order_activity_log(user, action, details)
-
6
BxBlockActivitylog::ActivityLog.create(
-
user: user,
-
action: action,
-
details: details,
-
accessed_at: Time.current
-
)
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ReturnExchangeRequestsController < ApplicationController
-
1
before_action :get_customer, only: [:create, :index]
-
1
before_action :set_return_exchange_request, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@return_exchange_requests = @customer.return_exchange_requests.all.order(created_at: :desc)
-
-
1
render json: @return_exchange_requests
-
end
-
-
1
def show
-
1
render json: @return_exchange_request
-
end
-
-
1
def create
-
3
order = Order.includes(:order_status).where('order_statuses.status': 'delivered').find_by(order_number: return_exchange_request_params[:order_number])
-
3
return render json: { error: 'Order not found' }, status: :not_found unless order
-
-
2
return_exchange_request = ReturnExchangeRequest.new(return_exchange_request_params)
-
2
return_exchange_request.order = order
-
2
return_exchange_request.customer = @customer
-
-
2
ActiveRecord::Base.transaction do
-
2
if return_exchange_request.save
-
1
add_order_items(return_exchange_request)
-
1
render json: return_exchange_request, status: :created
-
else
-
1
render json: return_exchange_request.errors, status: :unprocessable_entity
-
1
raise ActiveRecord::Rollback
-
end
-
end
-
end
-
-
1
def destroy
-
1
if @return_exchange_request.destroy
-
1
render json: {message: 'Return exchange request destroy'}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_return_exchange_request
-
2
@return_exchange_request = ReturnExchangeRequest.find(params[:id])
-
end
-
-
1
def return_exchange_request_params
-
5
params.require(:return_exchange_request).permit(:order_number, :customer_id, :request_type, :request_reason, :description, :order_id, :status, :custom_status, order_item_ids: [])
-
end
-
-
1
def get_customer
-
4
@customer = AccountBlock::Account.find_by(id: @token.id, user_type: 'buyer')
-
4
render json: {errors: 'Customer is invalid'} and return unless @customer.present?
-
end
-
-
1
def add_order_items(return_exchange_request)
-
1
order_status = BxBlockOrderManagement::OrderStatus.find_by(status: 'return')
-
1
order_items = return_exchange_request.order_items
-
-
1
if order_items.any?
-
2
order_items.each { |item| item.update!(order_status: order_status)}
-
end
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ReturnReasonDetailsController < ApplicationController
-
1
before_action :set_return_reason_detail, only: [:show, :update, :destroy]
-
-
1
def index
-
2
@return_reason_details = BxBlockShoppingCart::ReturnReasonDetail.all
-
2
@return_reason_details = @return_reason_details.where(shopping_cart_order_item_id: params[:order_item_id]) if params[:order_item_id].present?
-
2
@return_reason_details = @return_reason_details.where(reason_type: params[:reason_type]) if params[:reason_type].present?
-
-
2
render json: @return_reason_details.order(created_at: :desc), status: :ok
-
end
-
-
1
def show
-
render json: @return_reason_detail, status: :ok
-
end
-
-
1
def create
-
2
@return_reason_detail = ReturnReasonDetail.new(return_reason_detail_params)
-
-
2
if @return_reason_detail.save
-
1
render json: @return_reason_detail, status: :created
-
else
-
1
render json: @return_reason_detail.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @return_reason_detail.update(return_reason_detail_params)
-
1
render json: @return_reason_detail, status: :ok
-
else
-
1
render json: @return_reason_detail.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @return_reason_detail.destroy
-
1
render json: {message: 'return reason destroy'}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_return_reason_detail
-
3
@return_reason_detail = BxBlockShoppingCart::ReturnReasonDetail.find(params[:id])
-
end
-
-
1
def return_reason_detail_params
-
4
params.require(:return_reason_detail).permit(:title, :details, :shopping_cart_order_item_id, :reason_type)
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ShippedOrderDetailsController < ApplicationController
-
1
before_action :find_order, only: [:create]
-
1
before_action :set_shipped_order_detail, only: [:show, :update, :destroy]
-
-
1
def show
-
1
render json: @shipped_order_detail
-
end
-
-
1
def create
-
2
permitted_params = shipped_order_detail_params
-
2
order_item_ids = Array(permitted_params[:order_item_id])
-
-
2
last_created_record = nil
-
-
2
order_item_ids.each do |item_id|
-
2
shipped_order_detail = ShippedOrderDetail.new(
-
permitted_params.except(:order_item_id).merge(
-
order_item_id: item_id,
-
order_id: @order.id
-
)
-
)
-
2
if shipped_order_detail.save
-
2
last_created_record = shipped_order_detail
-
else
-
return render json: { errors: shipped_order_detail.errors, failed_id: item_id }, status: :unprocessable_entity
-
end
-
end
-
-
2
render json: last_created_record, status: :created
-
end
-
-
1
def update
-
2
if @shipped_order_detail.update(shipped_order_detail_params)
-
1
render json: @shipped_order_detail, status: :ok
-
else
-
1
render json: @shipped_order_detail.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @shipped_order_detail.destroy
-
1
render json: {message: "shipped order detail destroyed"}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_shipped_order_detail
-
4
@shipped_order_detail = ShippedOrderDetail.find(params[:id])
-
end
-
-
1
def find_order
-
2
@order = Order.find(params[:order_id])
-
end
-
-
1
def shipped_order_detail_params
-
4
params.require(:shipped_order_detail).permit(:shipping_details, :courier_name, :tracking_number, order_item_id: [])
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class TelrPaymentsController < ApplicationController
-
-
1
before_action :get_user
-
1
before_action :find_order
-
-
1
def create
-
2
if @order.order_status.status == 'on_going'
-
1
response = JSON.parse(post_gateway('create', @order, params))
-
1
if response['order'].present?
-
1
@order.update(transaction_id: response['order']['ref'])
-
end
-
1
render json: response, status: :ok
-
else
-
1
render json: {errors: "On going orders only accepted" }, status: :unprocessable_entity
-
end
-
end
-
-
1
def show_or_check
-
1
render json: post_gateway('check', @order, params), status: :ok
-
end
-
-
1
def payment_failed_notification
-
begin
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: @customer, subject: 'Sorry, your payment didn’t go through.', file: 'payment_failed_notification')
-
.notification
-
.deliver_now
-
-
1
render json: { message: 'Payment failed notification sent successfully.' }, status: :ok
-
rescue StandardError => e
-
Rails.logger.error("Failed to send payment failed notification: #{e.message}")
-
render json: { error: 'Failed to send payment failed notification.' }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def get_user
-
4
@customer = AccountBlock::Account.find_by(id: @token.id, user_type: 'buyer' )
-
4
render json: {errors: 'Customer is invalid'} and return unless @customer.present?
-
end
-
-
1
def find_order
-
4
@order = @customer.orders.find_by(id: params[:order_id])
-
4
render json: {errors: 'Order not found'} and return unless @order.present?
-
end
-
-
1
def post_gateway(action, order, params)
-
2
url = URI("https://secure.telr.com/gateway/order.json")
-
-
2
http = Net::HTTP.new(url.host, url.port)
-
2
http.use_ssl = true
-
-
2
request = Net::HTTP::Post.new(url)
-
2
request["accept"] = 'application/json'
-
2
request["Content-Type"] = 'application/json'
-
2
if action == 'create'
-
1
request.body = {
-
"method": "#{action}",
-
"store": ENV['TELR_STORE_ID'],
-
"authkey": ENV['TELR_AUTH_KEY'],
-
"framed": 0,
-
"order": {
-
"cartid":"#{order&.order_number}",
-
"test": ENV['TELR_LIVE_MODE'],
-
"amount":"#{params[:final_price]}",
-
"currency":"AED",
-
"description":"Ordered products are (#{order&.catalogues&.map(&:product_title)&.join(", ")})"
-
},
-
"return":{
-
"authorised":"#{ENV['FE_URL']}/checkout",
-
"declined":"#{ENV['FE_URL']}/order-summary",
-
"cancelled":"#{ENV['FE_URL']}/order-summary",
-
},
-
"customer": get_shipping_address(order)
-
}.to_json
-
else
-
1
request.body = {"method":"check", "store": ENV['TELR_STORE_ID'], "authkey": ENV['TELR_AUTH_KEY'], "order":{"ref": order&.transaction_id }}.to_json
-
end
-
-
2
response = http.request(request)
-
2
response.read_body
-
end
-
-
1
def get_shipping_address(order)
-
1
customer_details = {}
-
1
address = order.shipping_address
-
-
1
if address.present?
-
customer_details = {
-
"email": order&.customer&.email,
-
"name": {
-
"title": "",
-
"forenames": address.first_name,
-
"surname": address.last_name
-
},
-
"address": {
-
"line1": address.address_1,
-
"line2": address.address_2,
-
"line3": "",
-
"city": address.city,
-
"state": address.state,
-
"country": "AE",
-
"areacode": address.zip_code
-
}
-
}
-
end
-
-
1
customer_details
-
end
-
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class ApplicationController < BuilderBase::ApplicationController
-
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
-
1
private
-
-
1
def format_activerecord_errors(errors)
-
8
result = []
-
8
errors.each do |attribute, error|
-
20
attribute_name = attribute.to_s.gsub('_', ' ')
-
20
result << "#{attribute_name.capitalize} #{error}"
-
end
-
8
result
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreDashboardSectionsController < ApplicationController
-
1
before_action :validate_json_web_token, except: [:index, :show]
-
1
before_action :set_store
-
1
before_action :set_store_dashboard_section, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@store_dashboard_sections = @store.store_dashboard_sections.all.order(created_at: :asc)
-
-
1
render json: StoreDashboardSectionSerializer.new(@store_dashboard_sections), status: :ok
-
end
-
-
1
def show
-
1
render json: StoreDashboardSectionSerializer.new(@store_dashboard_section).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@store_dashboard_section = StoreDashboardSection.new(store_dashboard_section_params.merge(store_id: @store&.id))
-
-
2
if @store_dashboard_section.save
-
1
render json: StoreDashboardSectionSerializer.new(@store_dashboard_section).serializable_hash, status: :created
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@store_dashboard_section.errors) }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @store_dashboard_section.update(store_dashboard_section_params.merge(store_id: @store&.id))
-
1
render json: StoreDashboardSectionSerializer.new(@store_dashboard_section).serializable_hash, status: :ok
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@store_dashboard_section.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @store_dashboard_section.destroy
-
1
render json: {message: "Section removed"}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def store_dashboard_section_params
-
4
params.permit(:section_name, :section_type, :banner_name, :banner_image, :banner_url, store_section_grids_attributes: [:id, :grid_name, :grid_no, :grid_image, :grid_url, :_destroy])
-
end
-
-
1
def set_store
-
7
@store = Store.find(params[:store_id])
-
end
-
-
1
def set_store_dashboard_section
-
4
@store_dashboard_section = @store.store_dashboard_sections.find_by(id: params[:id])
-
4
if @store_dashboard_section.nil?
-
render json: {
-
message: "Section not found"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreMenusController < ApplicationController
-
1
before_action :set_store
-
1
before_action :set_menu, only: [:show, :update, :destroy]
-
1
before_action :validate_json_web_token, only: [:create, :update, :destroy]
-
-
1
def index
-
1
@menus = fetch_menus
-
1
render json: StoreMenuSerializer.new(@menus).serializable_hash, status: :ok
-
end
-
-
1
def store_menus_list
-
1
@menus = fetch_menus
-
1
render json: {store_menus: store_menu_response(@menus)}, status: :ok
-
end
-
-
1
def show
-
1
render json: StoreMenuSerializer.new(@menu).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@menu = @store.store_menus.create(menu_params)
-
2
if @menu.persisted?
-
1
if params[:catalogue_ids].present?
-
1
catalogue_ids = params[:catalogue_ids]
-
1
@menu.catalogues << BxBlockCatalogue::Catalogue.where(id: catalogue_ids)
-
end
-
1
render json: StoreMenuSerializer.new(@menu).serializable_hash, status: :created
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@menu.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @menu.update(menu_params)
-
1
if params[:catalogue_ids].present?
-
1
catalogue_ids = params[:catalogue_ids]
-
1
@menu.catalogues = BxBlockCatalogue::Catalogue.where(id: catalogue_ids)
-
end
-
1
render json: StoreMenuSerializer.new(@menu).serializable_hash, status: :ok
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@menu.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @menu.destroy
-
1
render json: {
-
message: "Menu removed"
-
}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_store
-
9
@store = Store.find(params[:store_id])
-
end
-
-
1
def set_menu
-
5
@menu = @store.store_menus.find_by(id: params[:id])
-
5
if @menu.nil?
-
1
render json: {
-
message: "Menu not found"
-
}, status: :not_found
-
end
-
end
-
-
1
def menu_params
-
4
params.permit(:title, :cover_image, :logo, :store_name, :banner_name, :position, :product_quantity)
-
end
-
-
1
def fetch_menus
-
2
@store.store_menus.order(position: :asc)
-
end
-
-
1
def store_menu_response(menus)
-
1
menus.map do |menu|
-
{
-
1
id: menu.id,
-
store_name: menu.store_name,
-
title: menu.title,
-
banner_name: menu.banner_name,
-
position: menu.position,
-
product_quantity: menu.product_quantity,
-
1
logo: (ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(menu.logo, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(menu.logo, only_path: true) if menu.logo.attached?),
-
1
cover_image: (ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(menu.cover_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(menu.cover_image, only_path: true) if menu.cover_image.attached?),
-
store_id: menu.store_id
-
}
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreSectionGridsController < ApplicationController
-
1
before_action :validate_json_web_token
-
1
before_action :set_store
-
1
before_action :set_store_dashboard_section
-
1
before_action :set_store_section_grid, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@store_section_grids = @store_dashboard_section.store_section_grids.all.order(created_at: :asc)
-
-
1
render json: StoreSectionGridSerializer.new(@store_section_grids), status: :ok
-
end
-
-
1
def show
-
1
render json: StoreSectionGridSerializer.new(@store_section_grid).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@store_section_grid = StoreSectionGrid.new(store_section_grid_params.merge(store_dashboard_section_id: @store_dashboard_section&.id))
-
-
2
if @store_section_grid.save
-
1
render json: StoreSectionGridSerializer.new(@store_section_grid).serializable_hash, status: :created
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@store_section_grid.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @store_section_grid.update(store_section_grid_params.merge(store_dashboard_section_id: @store_dashboard_section&.id))
-
1
render json: StoreSectionGridSerializer.new(@store_section_grid).serializable_hash, status: :ok
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@store_section_grid.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @store_section_grid.destroy
-
1
render json: {message: "Grid removed"}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def store_section_grid_params
-
4
params.permit( :grid_name, :grid_no, :grid_image, :grid_url)
-
end
-
-
1
def set_store
-
7
@store = Store.find(params[:store_id])
-
end
-
-
1
def set_store_dashboard_section
-
7
@store_dashboard_section = @store.store_dashboard_sections.find_by(id: params[:store_dashboard_section_id])
-
7
if @store_dashboard_section.nil?
-
render json: {
-
message: "Section not found"
-
}, status: :not_found
-
end
-
end
-
-
1
def set_store_section_grid
-
4
@store_section_grid = @store_dashboard_section.store_section_grids.find_by(id: params[:id])
-
4
if @store_section_grid.nil?
-
render json: {
-
message: "Grid not found"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoresController < ApplicationController
-
1
include BxBlockCatalogue::CatalogueSearch
-
1
before_action :set_store, only: [:show, :update, :destroy, :update_seller_store]
-
1
before_action :validate_json_web_token, only: [:create, :update, :destroy, :seller_store_listing, :update_seller_store, :create_seller_store, :delete_seller_store]
-
1
before_action :get_account, only: [:seller_store_listing, :update_seller_store, :create_seller_store, :delete_seller_store]
-
1
before_action :set_seller_store, only: [:delete_seller_store]
-
-
#listing of stores
-
-
1
def index
-
1
@stores = Store.all
-
1
render json: StoreSerializer.new(@stores).serializable_hash, status: :ok
-
end
-
-
1
def show
-
1
render json: StoreSerializer.new(@store).serializable_hash, status: :ok
-
end
-
-
1
def index_approved_stores
-
1
@stores = Store.all.where(approve: true).order(created_at: :desc)
-
-
1
render json: StoreSerializer.new(@stores, message: "Approved Stores Loaded").serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
@store = Store.create(store_params)
-
-
2
if @store.persisted?
-
1
render json: StoreSerializer.new(@store).serializable_hash, status: :created
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@store.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
2
if @store.update(store_params)
-
1
render json: StoreSerializer.new(@store).serializable_hash, status: :ok
-
else
-
1
render json: {
-
errors: format_activerecord_errors(@store.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def destroy
-
1
if @store.destroy
-
1
render json: {
-
message: 'Store has been successfully deleted'
-
}, status: :ok
-
end
-
end
-
-
-
1
def create_seller_store
-
2
store = @account.stores.new(store_params)
-
2
if store.save
-
1
render json: StoreSerializer.new(store).serializable_hash, status: :created
-
else
-
1
render json: { errors: store.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def seller_store_listing
-
1
per_page = params[:per_page].presence&.to_i || 10
-
1
page_number = params[:page].presence&.to_i || 1
-
1
@stores = @account.stores.order(created_at: :desc)
-
1
total_count = @stores.count
-
-
1
if @stores.present?
-
@stores = paginate_catalogues(@stores, page_number, per_page)
-
end
-
1
render json: StoreSerializer.new(@stores).serializable_hash.merge(total_count: total_count), status: :ok
-
end
-
-
1
def update_seller_store
-
2
if @store.update(store_params)
-
1
render json: StoreSerializer.new(@store).serializable_hash, status: :ok
-
else
-
1
render json: { errors: @store.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
1
def delete_seller_store
-
1
if @store.destroy
-
1
render json: {
-
message: 'Store has been successfully deleted'
-
}, status: :ok
-
end
-
end
-
-
1
private
-
-
1
def set_store
-
9
@store = Store.find_by(id: params[:id])
-
9
if @store.nil?
-
2
render json: {
-
message: "Store with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
1
def set_seller_store
-
2
@store = @account.stores.find_by(id: params[:id])
-
2
if @store.nil?
-
1
render json: {
-
message: "This store not belongs to your account or not exists with id #{params[:id]}"
-
}, status: :not_found
-
end
-
end
-
-
1
def get_account
-
9
@account = AccountBlock::Account.find_by(id: @token.id)
-
9
unless @account && @account.user_type == 'seller'
-
2
return render json: { errors: [{ message: "You are not authorized to access stores" }] }, status: :forbidden
-
end
-
end
-
-
1
def store_params
-
8
params.permit(:store_name, :store_year, :store_url, :website_social_url, :brand_trade_certificate, :brand_id)
-
end
-
-
end
-
end
-
1
module BxBlockSupport
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockSupport
-
1
class SocialPlatformsController < ApplicationController
-
1
before_action :set_social_platform, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@social_platforms = SocialPlatform.all
-
-
2
render json: @social_platforms.map { |platform| social_platform_data(platform) }
-
end
-
-
1
def show
-
1
render json: social_platform_data(@social_platform)
-
end
-
-
1
private
-
-
1
def set_social_platform
-
2
@social_platform = SocialPlatform.find(params[:id])
-
end
-
-
1
def social_platform_data(platform)
-
2
social_icon_url = if platform.social_icon.attached?
-
2
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(platform.social_icon, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(platform.social_icon, only_path: true)
-
end
-
-
{
-
2
id: platform.id,
-
social_media: platform.social_media,
-
social_media_url: platform.social_media_url,
-
social_icon: social_icon_url
-
}
-
end
-
-
end
-
end
-
1
module BxBlockSupport
-
1
class StaticPagesController < ApplicationController
-
1
before_action :set_static_page, only: [:show, :update, :destroy]
-
-
1
def index
-
1
@static_pages = StaticPage.all.where(status: true)
-
-
1
render json: @static_pages
-
end
-
-
1
def show
-
1
render json: @static_page
-
end
-
-
1
def delete_static_pages
-
2
if params[:ids].present?
-
1
pages = StaticPage.where(id: params[:ids])
-
1
if pages.destroy_all
-
1
render json: { message: 'Pages deleted successfully' }, status: :ok
-
end
-
else
-
1
render json: { error: 'No IDs provided' }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def set_static_page
-
1
@static_page = StaticPage.find_by(id: params[:id],status: true)
-
end
-
-
end
-
end
-
1
module BxBlockSupport
-
1
class SupportDocumentsController < ApplicationController
-
1
before_action :set_support_document, only: [:show]
-
-
1
def index
-
1
@support_documents = SupportDocument.all
-
-
1
render json: @support_documents
-
end
-
-
1
def show
-
1
render json: @support_document
-
end
-
-
1
def delete_support_documents
-
2
if params[:ids].present?
-
1
documents = SupportDocument.where(id: params[:ids])
-
1
if documents.destroy_all
-
1
render json: { message: 'Documents deleted successfully' }, status: :ok
-
end
-
else
-
1
render json: { error: 'No IDs provided' }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def set_support_document
-
1
@support_document = SupportDocument.find(params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockSupport
-
1
class SupportsController < ApplicationController
-
-
1
def create
-
2
support_params = jsonapi_deserialize(params)
-
-
2
validator = AccountBlock::EmailValidation.new(support_params["email"])
-
-
2
if !validator.valid?
-
1
return render json: { errors: [{ account: "Email invalid" }] }, status: :unprocessable_entity
-
end
-
-
1
@support = Support.new(support_params)
-
-
1
if @support.save
-
1
render json: @support, status: :created
-
else
-
render json: @support.errors, status: :unprocessable_entity
-
end
-
end
-
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class PrivacyAndLegalPolicyController < ApplicationController
-
1
before_action :set_privacy_and_policy, only: [:show]
-
-
1
def index
-
1
privacy_policy = PrivacyAndLegalPolicy.all.where(status: true)
-
1
render json: PrivacyAndLegalPolicySerializer.new(privacy_policy).serializable_hash
-
end
-
-
1
def show
-
1
render json: PrivacyAndLegalPolicySerializer.new(@privacy_policy).serializable_hash
-
end
-
-
1
private
-
-
1
def set_privacy_and_policy
-
1
@privacy_policy = PrivacyAndLegalPolicy.find(params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class SellerStaticPagesController < ApplicationController
-
1
before_action :set_seller_static_page, only: [:show]
-
-
1
def index
-
1
@seller_static_pages = SellerStaticPage.all.where(status: true)
-
-
1
render json: @seller_static_pages
-
end
-
-
1
def show
-
1
render json: @seller_static_page
-
end
-
-
1
def delete_static_pages
-
2
if params[:ids].present?
-
1
pages = SellerStaticPage.where(id: params[:ids])
-
1
if pages.destroy_all
-
1
render json: { message: 'Pages deleted successfully' }, status: :ok
-
end
-
else
-
1
render json: { error: 'No IDs provided' }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def set_seller_static_page
-
2
@seller_static_page = SellerStaticPage.find(params[:id])
-
end
-
-
# def seller_static_page_params
-
# params.require(:seller_static_page).permit(:title, :content, :status)
-
# end
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class TermsPoliciesController < ApplicationController
-
1
before_action :set_terms_policy, only: [:show]
-
-
1
def index
-
1
@terms_policies = TermsPolicy.all
-
-
1
render json: @terms_policies
-
end
-
-
1
def show
-
1
render json: @terms_policy
-
end
-
-
1
private
-
-
1
def set_terms_policy
-
1
@terms_policy = TermsPolicy.find(params[:id])
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
module CatalogueSearch
-
1
extend ActiveSupport::Concern
-
1
CATEGORY_QUERY = 'LOWER(name) = ?'
-
1
def filter_catalogues(catalogues,params)
-
5
catalogues = catalogues.where(status: params[:live_status]) if params[:live_status].present?
-
5
catalogues = catalogues.where(content_status: params[:content_status]) if params[:content_status].present?
-
5
if params[:fulfillment].present?
-
1
fulfilled_type = params[:fulfillment]
-
-
1
catalogues = catalogues.where(
-
"fulfilled_type = :fulfilled_type OR id IN (
-
SELECT DISTINCT parent_product_id FROM catalogues
-
WHERE fulfilled_type = :fulfilled_type AND parent_product_id IS NOT NULL
-
)",
-
fulfilled_type: fulfilled_type
-
)
-
end
-
5
catalogues
-
end
-
-
1
def product_search_by_title(product_keyword, catalogues_scope, search_by)
-
#here sku added because it is needed for search catalogue by title/sku api for seller side api
-
5
query = 'LOWER(catalogues.product_title) LIKE :query '
-
5
query += 'OR LOWER(catalogues.sku) LIKE :query OR LOWER(product_variant_groups.product_sku) LIKE :query' if search_by == "include_sku"
-
5
catalogues_scope.where(query, query: "%#{product_keyword.downcase}%")
-
end
-
-
1
def variant_product_search(product_keyword, seller, brand_id = nil)
-
5
variant_catalogues = Catalogue
-
.includes(:variant_products, :product_variant_group)
-
.references(:variant_products, :product_variant_group)
-
.where("LOWER(product_variant_groups.product_sku) LIKE :query OR LOWER(variant_products_catalogues.sku) LIKE :query OR LOWER(variant_products_catalogues.product_title) LIKE :query", query: "%#{product_keyword.downcase}%")
-
.where(seller: seller)
-
-
5
variant_catalogues = variant_catalogues.where(brand_id: brand_id) if brand_id.present?
-
-
5
variant_catalogues
-
end
-
-
1
def brand_ids_by_brand_name_keyword(keywords)
-
4
return [] unless keywords.present?
-
8
brand_conditions = keywords.map { |keyword| "LOWER(brand_name) LIKE '%#{keyword.downcase}%'" }.join(' OR ')
-
4
Brand.where(brand_conditions).pluck(:id)
-
end
-
-
1
def apply_category_filters(catalogues)
-
17
catalogues.where!(category_id: params[:category_ids]) if params[:category_ids].present?
-
17
catalogues.where!(sub_category_id: params[:sub_category_ids]) if params[:sub_category_ids].present?
-
17
catalogues.where!(mini_category_id: params[:mini_category_ids]) if params[:mini_category_ids].present?
-
17
catalogues.where!(micro_category_id: params[:micro_category_ids]) if params[:micro_category_ids].present?
-
17
catalogues.where!(brand_id: params[:brand_ids]) if params[:brand_ids].present?
-
end
-
-
1
def apply_price_filters(catalogues, min_price, max_price)
-
-
13
min_price_decimal = min_price.present? ? BigDecimal(min_price) : nil
-
13
max_price_decimal = max_price.present? ? BigDecimal(max_price) : nil
-
-
13
catalogues.where('final_price >= ? AND final_price <= ?', min_price_decimal, max_price_decimal) if min_price_decimal.present? && max_price_decimal.present?
-
-
end
-
-
1
def filter_by_colors(catalogues, color_filter)
-
-
13
catalogues.joins(:product_content)
-
.where('product_contents.product_color IN (?)',color_filter)
-
-
end
-
-
1
def get_min_max_value(catalogues)
-
29
catalogues = catalogues.order("final_price DESC")
-
29
min_range = catalogues.last&.final_price || 0
-
29
max_range = catalogues.first&.final_price || min_range || 0
-
29
[min_range,max_range]
-
end
-
-
1
def sort_catalogues(catalogues, sort_by)
-
18
case sort_by
-
when 'low_to_high'
-
catalogues.low_to_high
-
-
when 'high_to_low'
-
catalogues.high_to_low
-
-
when 'product_title_AZ'
-
catalogues.product_title_AZ
-
-
when 'product_title_ZA'
-
catalogues.product_title_ZA
-
-
when 'whats_new'
-
14
catalogues.whats_new
-
-
when 'recommended'
-
1
catalogues.recommended
-
-
when 'customer_rating'
-
1
sorted_catalogues_avg_rating(catalogues)
-
-
when 'popularity'
-
1
catalogues.popularity
-
-
else
-
1
catalogues
-
end
-
end
-
-
1
def paginate_catalogues(catalogues, page, per_page)
-
49
catalogues.page(page).per(per_page)
-
end
-
-
1
def render_search_results(catalogues, min_range, max_range, category, total_count = 0)
-
25
message = catalogues.present? ? "Successfully Loaded" : "No products found"
-
25
render json: CatalogueSerializer.new(catalogues).serializable_hash.merge({category: category, min_range: min_range,
-
max_range: max_range,
-
total_count: total_count,
-
message: message}), status: :ok
-
end
-
-
1
def find_brand(brand_name)
-
21
BxBlockCatalogue::Brand.where('LOWER(brand_name) = ?', brand_name&.strip&.downcase).first
-
end
-
-
1
def find_category(category_name)
-
20
BxBlockCategories::Category.where(CATEGORY_QUERY, category_name&.strip&.downcase).first
-
end
-
-
1
def find_subcategory(subcategory_name)
-
20
BxBlockCategories::SubCategory.where(CATEGORY_QUERY, subcategory_name&.strip&.downcase).first
-
end
-
-
1
def find_minicategory(minicategory_name)
-
20
BxBlockCategories::MiniCategory.where(CATEGORY_QUERY, minicategory_name&.strip&.downcase).first
-
end
-
-
1
def find_microcategory(microcategory_name)
-
20
BxBlockCategories::MicroCategory.where(CATEGORY_QUERY, microcategory_name&.strip&.downcase).first
-
end
-
-
1
def render_no_product_found
-
4
render json: { data: [], message: "No products found", total_count: 0 }, status: :not_found
-
end
-
-
1
def render_no_result_found
-
4
render json: { message: "No result found" }, status: :not_found
-
end
-
-
#rating common methods
-
-
1
def sorted_catalogues_avg_rating(catalogues)
-
1
subquery = BxBlockCatalogue::Review.approved_reviews.select('catalogue_id, AVG(rating) AS avg_rating')
-
.where(review_type: 'product')
-
.group('catalogue_id')
-
-
1
catalogues.joins("LEFT JOIN (#{subquery.to_sql}) AS avg_ratings ON catalogues.id = avg_ratings.catalogue_id")
-
.order('avg_ratings.avg_rating DESC NULLS LAST')
-
end
-
-
1
def average_rating(reviews)
-
55
return 0 if reviews.empty?
-
37
reviews.sum(&:rating).to_f / reviews.count
-
end
-
-
1
def seller_rating_percentage(reviews)
-
6
total_reviews = reviews.count
-
6
return {} if total_reviews.zero?
-
-
6
percentages = {}
-
6
(1..5).each do |rating|
-
70
rating_count = reviews.select {|review| review.rating.to_i == rating}.count
-
30
percentages[rating] = ((rating_count.to_f / total_reviews.to_f) * 100).round(2)
-
end
-
6
percentages
-
end
-
-
1
def total_rating(reviews)
-
6
reviews.sum(&:rating)
-
end
-
-
1
def filter_by_custom_field_values(catalogues, custom_field_values)
-
3
query = []
-
3
custom_field_values.each do |value|
-
6
query << BxBlockCatalogue::CatalogueContent.where(value: value).where(catalogue_id: catalogues.pluck(:id)).pluck(:catalogue_id)
-
end
-
3
catalogues.where(id: query.flatten)
-
end
-
-
1
def filter_by_ratings(catalogues, params)
-
14
rating_result = []
-
14
if params.present?
-
14
ratings = params.map(&:to_i)
-
14
min_rating = ratings.min
-
-
14
rating_result = catalogues.select do |catalogue|
-
49
reviews = catalogue.review_and_ratings.approved_reviews.where(review_type: 'product')
-
49
average_rating = average_rating(reviews)
-
-
49
average_rating >= min_rating
-
end.map(&:id)
-
end
-
14
catalogues.where(id: rating_result)
-
end
-
-
1
def catalogues_by_active_deals(deal_id)
-
3
DealCatalogue.all.where(deal_id: deal_id, status: 'approved').pluck(:catalogue_id)
-
end
-
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
module OrderConcern
-
1
extend ActiveSupport::Concern
-
-
1
def get_delivery_address(order)
-
41
delivery_address = order.shipping_address
-
-
41
if order.shipping_first_name.blank?
-
39
return AccountBlock::UserDeliveryAddressSerializer.new(delivery_address)
-
end
-
-
{
-
2
data: {
-
id: delivery_address&.id,
-
type: "user_delivery_address",
-
attributes: {
-
address_status: "ordered",
-
first_name: order.shipping_first_name,
-
last_name: order.shipping_last_name,
-
address_1: order.shipping_address_1,
-
address_2: order.shipping_address_2,
-
phone_number: order.shipping_phone_number,
-
state: order.shipping_state,
-
city: order.shipping_city,
-
zip_code: order.shipping_zip_code,
-
account_id: delivery_address&.account_id,
-
is_default: delivery_address&.is_default
-
}
-
}
-
}
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
module ApplicationHelper
-
end
-
end
-
1
module BxBlockStripeIntegration
-
1
module ApplicationHelper
-
end
-
end
-
1
class ApplicationJob < ActiveJob::Base
-
# Automatically retry jobs that encountered a deadlock
-
# retry_on ActiveRecord::Deadlocked
-
-
# Most jobs are safe to ignore if the underlying records are no longer available
-
# discard_on ActiveJob::DeserializationError
-
end
-
1
module BuilderBase
-
1
class ApplicationJob < ::ApplicationJob
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ExpireOffersAndDealsJob < ApplicationJob
-
1
queue_as :default
-
-
1
def perform(*args)
-
# Expire catalogue offers
-
3
CatalogueOffer.where('sale_schedule_to < ?', Time.current).find_each do |offer|
-
3
offer.update(status: false) # Set inactive
-
end
-
-
# Expire deals
-
3
Deal.where('end_date < ?', Time.current).find_each do |deal|
-
3
deal.status = false
-
3
deal.save(validate: false) # Deactivate deal
-
3
deal.deal_catalogues.update_all(status: :expired)
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: "from@example.com"
-
1
layout "mailer"
-
end
-
end
-
1
module AccountBlock
-
1
class EmailValidationMailer < ApplicationMailer
-
-
1
def activation_email
-
2
account_variables
-
-
2
mailer_call(@account,"Account activation","activation_email")
-
end
-
-
1
def welcome_email
-
2
account_variables
-
-
2
mailer_call(@account,@message,"welcome_email")
-
end
-
-
1
private
-
-
1
def encoded_token
-
4
BuilderJsonWebToken.encode @account.id, 10.minutes.from_now
-
end
-
-
1
def account_variables
-
4
@account = params[:account]
-
4
@host = Rails.env.development? ? "http://localhost:3000" : ENV['FE_URL']
-
-
4
@token = encoded_token
-
4
@reset_password = @account.user_type == 'buyer' ? "#{@host}/buyer/forgotpassword?verify=#{@token}" : "#{@host}/seller/forgotpassword?verify=#{@token}"
-
-
4
@url = @account.user_type == 'buyer' ? "#{@host}/buyer/otp?verify=#{@token}" : "#{@host}/seller/otp?verify=#{@token}"
-
4
@message = @account.user_type == 'buyer' ? "Welcome to Byezzy – Your neighbourhood marketplace for everything you need and more!" : "Welcome to Byezzy!!"
-
end
-
-
1
def mailer_call(account,message,file)
-
4
mail(
-
to: account.email,
-
from: "admin_notification@byezzy.com",
-
subject: message
-
) do |format|
-
8
format.html { render file }
-
end
-
end
-
end
-
end
-
1
class ApplicationMailer < ActionMailer::Base
-
1
default from: 'from@example.com'
-
1
layout 'mailer'
-
end
-
1
module BuilderBase
-
1
class ApplicationMailer < ::ApplicationMailer
-
1
default from: 'care@byezzy.com'
-
1
layout 'mailer'
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: "from@example.com"
-
1
layout "mailer"
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class BrandApprovalMailer < ApplicationMailer
-
1
def brand_approval_email
-
2
@account = params[:account]
-
2
@host = Rails.env.development? ? 'http://localhost:3000' : params[:host]
-
2
mail(
-
to: @account.email,
-
from: 'admin_notification@byezzy.com',
-
subject: ' ByEzzy brand approval update') do |format|
-
4
format.html { render 'brand_approval_email' }
-
end
-
end
-
end
-
end
-
-
1
module BxBlockContactUs
-
1
class AdminReplyMailer < ApplicationMailer
-
1
def notification(admin_reply)
-
5
@admin_reply = admin_reply
-
5
if @admin_reply.image.attached?
-
3
attachments.inline[@admin_reply.image.filename.to_s] = @admin_reply.image.download
-
3
@admin_image_url = attachments.inline[@admin_reply.image.filename.to_s].url
-
else
-
2
@admin_image_url = nil
-
end
-
5
if @admin_reply.contact.image.attached?
-
4
attachments.inline[@admin_reply.contact.image.filename.to_s] = @admin_reply.contact.image.download
-
4
@admin_contact_image_url = attachments.inline[@admin_reply.contact.image.filename.to_s].url
-
else
-
1
@admin_contact_image_url = nil
-
end
-
5
mail(to: admin_reply.contact.email, subject: ' Admin Reply Notification')
-
end
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: 'care@byezzy.com'
-
1
layout 'mailer'
-
end
-
end
-
1
module BxBlockEmailNotifications
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: 'from@example.com'
-
1
layout 'mailer'
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: 'from@example.com'
-
1
layout 'mailer'
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class ForgotPasswordMailer < ApplicationMailer
-
1
def reset_email
-
3
@account = params[:account]
-
3
@host = Rails.env.development? ? "http://localhost:3000" : ENV['FE_URL']
-
-
3
token = params[:token]
-
-
3
@url = @account.user_type == 'buyer' ? "#{@host}/buyer/forgotpassword?verify=#{token}" : "#{@host}/seller/forgotpassword?verify=#{token}"
-
-
3
mail(
-
to: @account.email,
-
from: "admin_notification@byezzy.com",
-
subject: "Reset Password"
-
) do |format|
-
6
format.html { render "reset_password_email" }
-
end
-
end
-
-
end
-
end
-
1
module AccountBlock
-
1
class Account < AccountBlock::ApplicationRecord
-
1
ActiveSupport.run_load_hooks(:account, self)
-
1
self.table_name = :accounts
-
-
1
include Wisper::Publisher
-
-
1
has_secure_password
-
1
before_validation :parse_full_phone_number
-
1
before_create :generate_api_key
-
1
has_one :blacklist_user, class_name: "AccountBlock::BlackListUser", dependent: :destroy
-
1
after_save :set_black_listed_user
-
1
before_save :set_full_name
-
-
1
enum status: %i[regular suspended deleted]
-
-
1
scope :active, -> { where(activated: true) }
-
1
scope :existing_accounts, -> { where(status: ["regular", "suspended"]) }
-
13
scope :buyer_accounts, -> { where(user_type: 'buyer') }
-
85
scope :seller_accounts, -> { where(user_type: 'seller') }
-
-
1
validates :email, :full_phone_number, presence: true
-
1
validate :email_uniqueness_within_user_type
-
1
validate :phone_number_uniqueness_within_user_type
-
-
1
validate :valid_phone_number
-
1
has_many :seller_documents, class_name: "AccountBlock::SellerDocument", dependent: :destroy
-
1
has_many :suggestion_feedbacks, class_name: "AccountBlock::SuggestionFeedback", dependent: :destroy
-
1
has_many :user_delivery_addresses, class_name: "AccountBlock::UserDeliveryAddress", dependent: :destroy
-
1
has_many :brands, class_name: "BxBlockCatalogue::Brand", dependent: :destroy
-
1
has_many :favourites, class_name: "BxBlockFavourites::Favourite", foreign_key: "user_id", dependent: :destroy
-
1
has_many :orders, class_name: 'BxBlockShoppingCart::Order', foreign_key: :customer_id, dependent: :destroy
-
1
has_many :return_exchange_requests, class_name: 'BxBlockShoppingCart::ReturnExchangeRequest', foreign_key: :customer_id, dependent: :destroy
-
1
has_many :stores, class_name: "BxBlockStoreManagement::Store", dependent: :destroy
-
1
has_many :subscribe_coupons, class_name: "BxBlockCouponCg::SubscribeCoupon", dependent: :destroy
-
1
has_many :coupon_codes, through: :subscribe_coupons, class_name: "BxBlockCouponCg::CouponCode", source: :coupon
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :deal_catalogues, class_name: "BxBlockCatalogue::DealCatalogue", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :warehouses, class_name: "BxBlockCatalogue::Warehouse", dependent: :destroy
-
1
has_many :review_and_ratings, class_name: "BxBlockCatalogue::Review", dependent: :destroy
-
1
has_many :addresses, class_name:"BxBlockAddress::Address", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :catalogue_variants, class_name: "BxBlockCatalogue::CatalogueVariant", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :restricted_brands, class_name: "BxBlockCatalogue::RestrictedBrand", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :delivery_requests, class_name: 'BxBlockOrderManagement::DeliveryRequest', dependent: :destroy, foreign_key: 'seller_id'
-
1
has_many :activity_logs, class_name: "BxBlockActivitylog::ActivityLog", foreign_key: :user_id, dependent: :nullify
-
1
has_many :wms_product_infos, class_name: "BxBlockOrderManagement::WmsProductInfo", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :wms_consignment_orders, class_name: "BxBlockOrderManagement::WmsConsignmentOrder", foreign_key: :seller_id, dependent: :destroy
-
1
has_many :invoice_billings, class_name: 'BxBlockInvoicebilling::InvoiceBilling', foreign_key: :customer_id, dependent: :destroy
-
1
has_many :product_views, class_name: "BxBlockSalesreporting::ProductView", foreign_key: :user_id, dependent: :destroy
-
-
1
accepts_nested_attributes_for :addresses
-
1
has_one_attached :profile_picture
-
-
1
before_save :set_default_language
-
-
1
private
-
-
1
def parse_full_phone_number
-
3275
phone = Phonelib.parse(full_phone_number)
-
3275
self.full_phone_number = phone.sanitized
-
3275
self.country_code = phone.country_code
-
3275
self.phone_number = phone.raw_national
-
end
-
-
1
def valid_phone_number
-
3275
unless Phonelib.valid?(full_phone_number)
-
1
errors.add(:full_phone_number,"Invalid or Unrecognized")
-
end
-
end
-
-
1
def generate_api_key
-
2749
loop do
-
2749
@token = SecureRandom.base64.tr("+/=", "Qrt")
-
2749
break @token unless Account.exists?(unique_auth_id: @token)
-
end
-
2749
self.unique_auth_id = @token
-
end
-
-
1
def set_black_listed_user
-
3272
if is_blacklisted_previously_changed?
-
if is_blacklisted
-
AccountBlock::BlackListUser.create(account_id: id)
-
else
-
blacklist_user.destroy
-
end
-
end
-
end
-
-
1
def set_full_name
-
3272
self.full_name = "#{first_name} #{last_name}"
-
end
-
-
1
def email_uniqueness_within_user_type
-
3275
if Account.where(email: email, user_type: user_type).where.not(id: id).exists?
-
2
errors.add(:email, "has already been taken")
-
end
-
end
-
-
1
def phone_number_uniqueness_within_user_type
-
3275
if Account.where(full_phone_number: full_phone_number, user_type: user_type).where.not(id: id).exists?
-
errors.add(:full_phone_number, "has already been taken")
-
end
-
end
-
-
1
def set_default_language
-
3272
self.language = 'English' if self.language.blank?
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module AccountBlock
-
1
class BlackListUser < AccountBlock::ApplicationRecord
-
1
self.table_name = :black_list_users
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
-
1
def user_mobile_number
-
account.full_phone_number
-
end
-
-
1
def user_email
-
account.email
-
end
-
-
1
def user_type
-
account.user_type
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SellerDocument < AccountBlock::ApplicationRecord
-
1
self.table_name = :seller_documents
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
-
DOCUMENT_TYPES = {
-
1
trading_license: 'Trading License or Commercial Registration',
-
passport: 'Passport or Residence ID',
-
residence_visa: 'Residence visa for non-nationals',
-
vat_certificate: 'VAT Certificate or Reason for not having it',
-
iban_certificate: 'IBAN Certificate or Bank Details'
-
}.freeze
-
-
# Document type validations
-
1
validates :document_type, presence: true, inclusion: { in: DOCUMENT_TYPES.values }
-
-
# Document name and file upload associations
-
1
has_many_attached :document_files, dependent: :destroy
-
-
1
validate :only_one_status_selected
-
-
# Additional fields for specific document types
-
1
validate :validate_documents
-
1
validates :vat_reason, presence: true, if: :vat_certificate_with_reason?
-
1
validates :account_no, :iban, :bank_address, :name, :bank_name, :swift_code, presence: true, if: :iban_certificate_without_file?
-
1
before_update :remove_vat_reason, if: :vat_document_present?
-
1
before_update :remove_iban_attributes, if: :iban_document_present?
-
-
1
after_update :account_verification_notification
-
-
1
private
-
-
1
def only_one_status_selected
-
87
if approved? && rejected?
-
1
errors.add(:base, "Only one status can be selected: either 'approved' or 'rejected', but not both.")
-
end
-
end
-
-
1
def validate_documents
-
87
unless [DOCUMENT_TYPES[:residence_visa], DOCUMENT_TYPES[:vat_certificate], DOCUMENT_TYPES[:iban_certificate]].include?(document_type) || document_files.present?
-
3
errors.add(:document_files, "must be attached")
-
end
-
end
-
-
-
1
def vat_certificate_with_reason?
-
87
document_type == DOCUMENT_TYPES[:vat_certificate] && document_files.blank?
-
end
-
-
1
def iban_certificate_without_file?
-
87
document_type == DOCUMENT_TYPES[:iban_certificate] && !document_files.attached?
-
end
-
-
1
def vat_document_present?
-
8
document_type == DOCUMENT_TYPES[:vat_certificate] && document_files.present?
-
end
-
-
1
def iban_document_present?
-
8
document_type == DOCUMENT_TYPES[:iban_certificate] && document_files.present?
-
end
-
-
1
def remove_vat_reason
-
1
self.vat_reason = nil
-
end
-
-
1
def remove_iban_attributes
-
1
self.account_no = nil
-
1
self.iban = nil
-
1
self.bank_address = nil
-
1
self.name = nil
-
1
self.bank_name = nil
-
1
self.swift_code = nil
-
end
-
-
1
def account_verification_notification
-
8
if all_documents_verified?
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: account, subject: 'Account Verification Successful', file: 'account_verification_success')
-
.notification.deliver_now
-
7
elsif rejected_status_changed?
-
3
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: account, subject: 'Account Verification Failed', file: 'document_or_account_verification_failure')
-
.notification.deliver_now
-
else
-
4
puts " "
-
end
-
end
-
-
1
def all_documents_verified?
-
8
account.seller_documents.where(approved: true).count == DOCUMENT_TYPES.size
-
end
-
-
1
def any_document_rejected?
-
account.seller_documents.where(rejected: true).exists?
-
end
-
-
1
def rejected_status_changed?
-
7
saved_change_to_rejected? && rejected?
-
end
-
-
end
-
end
-
1
module AccountBlock
-
1
class SmsOtp < ApplicationRecord
-
1
self.table_name = :sms_otps
-
-
1
include Wisper::Publisher
-
-
1
before_validation :parse_full_phone_number
-
-
1
before_create :generate_pin_and_valid_date
-
1
after_create :send_pin_via_sms
-
-
1
validate :valid_phone_number
-
1
validates :full_phone_number, presence: true
-
-
1
attr_reader :phone
-
-
-
1
def generate_pin_and_valid_date
-
6
self.pin = rand(1_0000..9_9999)
-
6
self.valid_until = Time.current + 5.minutes
-
end
-
-
1
def send_pin_via_sms
-
9
message = "Your Pin Number is #{pin}"
-
9
txt = BxBlockSms::SendSms.new("+#{full_phone_number}", message)
-
9
txt.call
-
end
-
-
1
private
-
-
1
def parse_full_phone_number
-
12
@phone = Phonelib.parse(full_phone_number)
-
12
self.full_phone_number = @phone.sanitized
-
end
-
-
1
def valid_phone_number
-
12
unless Phonelib.valid?(full_phone_number)
-
1
errors.add(:full_phone_number, "Invalid or Unrecognized Phone Number")
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SuggestionFeedback < AccountBlock::ApplicationRecord
-
1
self.table_name = :suggestion_feedbacks
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
validates :email, :first_name,:last_name,:detail_type,:detail, presence: true
-
end
-
end
-
1
module AccountBlock
-
1
class UserDeliveryAddress < ApplicationRecord
-
1
self.table_name = :user_delivery_addresses
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
has_many :orders, class_name: 'BxBlockShoppingCart::Order', foreign_key: :address_id
-
-
1
validates :first_name, :last_name, :address_1, :address_2, :phone_number, :state, :city, presence: true
-
-
# validate :valid_phone_number
-
-
1
before_save :check_and_update_default
-
1
after_save :modify_order_shipping_address
-
-
1
before_destroy :nullify_order_address
-
-
# def valid_phone_number
-
# unless Phonelib.valid?(phone_number)
-
# errors.add(:phone_number,"Invalid or Unrecognized")
-
# end
-
# end
-
-
1
private
-
-
1
def nullify_order_address
-
1
orders.update_all(address_id: nil)
-
end
-
-
1
def check_and_update_default
-
9
return unless is_default?
-
-
6
account.user_delivery_addresses.where.not(id: id).update_all(is_default: false)
-
end
-
-
1
def modify_order_shipping_address
-
9
if is_default? && account.orders.present?
-
1
order = account.orders.includes(:order_status).find_by(order_statuses: { status: ["scheduled"] })
-
1
order.update(address_id: id) if order
-
end
-
end
-
-
end
-
end
-
1
class AdminUser < ApplicationRecord
-
# Include default devise modules. Others available are:
-
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
-
1
devise :database_authenticatable,
-
:recoverable, :rememberable, :validatable
-
end
-
1
class ApplicationRecord < ActiveRecord::Base
-
1
self.abstract_class = true
-
end
-
1
module BuilderBase
-
1
class ApplicationRecord < ::ApplicationRecord
-
1
self.abstract_class = true
-
1
self.store_full_sti_class = false
-
end
-
end
-
1
module BxBlockActivitylog
-
1
class ActivityLog < ApplicationRecord
-
1
self.table_name = :activity_logs
-
1
belongs_to :user, class_name: "AccountBlock::Account", optional: true
-
-
1
before_save :assign_user_type
-
1
scope :by_user_type, ->(user_type) { where(user_type: user_type) }
-
-
1
private
-
-
1
def assign_user_type
-
26
if user
-
25
self.user_type = user.user_type
-
25
self.user_email = user.email
-
25
self.accessed_at = Time.current
-
end
-
end
-
end
-
end
-
1
module BxBlockActivitylog
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAddress
-
1
class Address < ApplicationRecord
-
1
self.table_name = :addresses
-
-
# belongs_to :account, class_name: "AccountBlock::Account",
-
# foreign_key: "seller_id"
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
-
1
reverse_geocoded_by :latitude, :longitude
-
-
# enum address_type: {"Home" => 0, "Work" => 1, "Other" => 2}
-
-
# validates :address_type, presence: true
-
-
# after_validation :reverse_geocode
-
-
# before_create :add_address_type
-
-
1
private
-
-
1
def add_address_type
-
self.address_type = "Home" unless address_type.present?
-
end
-
end
-
end
-
1
module BxBlockAddress
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAttachment
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAttachment
-
1
class Attachment < BxBlockAttachment::ApplicationRecord
-
1
self.table_name = :attachments
-
1
include Wisper::Publisher
-
-
1
has_one_attached :attachment
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
after_create :default_values
-
1
scope :not_expired, -> {where('is_expired = ?',false)}
-
-
1
def default_values
-
self.colour = "Greyscale"
-
self.layout = "Portrait"
-
self.page_size = "A4"
-
self.print_sides = "Both"
-
self.scale = "Print all pages"
-
self.print_pages_from = 1
-
self.print_pages_to = 1
-
self.total_pages = 1
-
end
-
-
1
def self.attachment_expire
-
attachments = BxBlockAttachment::Attachment.where(
-
"created_at + '4 hours'::interval < ? AND is_expired =?", DateTime.now, false
-
)
-
if attachments.present?
-
attachments.each do |attachment|
-
broadcast(:attachment_expired, attachment)
-
attachment.update_attributes(:is_expired => true)
-
if attachment.attachment.attached?
-
attachment.attachment.purge
-
attachment.destroy
-
end
-
end
-
end
-
-
expired_attachments = BxBlockAttachment::Attachment.where(
-
"created_at + '4 hours'::interval < ? AND is_expired =?", DateTime.now, true
-
)
-
if expired_attachments.present?
-
expired_attachments.each do |at|
-
at.destroy
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class AttributeOption < ApplicationRecord
-
1
self.table_name = :attribute_options
-
-
1
belongs_to :variant_attribute, class_name: "BxBlockCatalogue::VariantAttribute"
-
-
1
has_many :group_attributes, class_name: "BxBlockCatalogue::GroupAttribute", dependent: :destroy
-
1
validates :option, presence: true
-
-
1
before_save :update_group_attributes
-
-
1
private
-
-
1
def update_group_attributes
-
12
if option_changed?
-
12
group_attributes.update_all(option: option)
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Barcode < ApplicationRecord
-
1
self.table_name = :barcodes
-
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
validates :bar_code, presence: true
-
1
has_one :catalogue_offer, class_name: "BxBlockCatalogue::CatalogueOffer", dependent: :destroy
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Brand < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :brands
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
has_one_attached :branding_tradmark_certificate, dependent: :destroy
-
1
validates :brand_name, presence: true, uniqueness: { case_sensitive: false }
-
1
VALID_URL_REGEX = /\A((http|https):\/\/)?(www\.)?[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+(\S*)?\z/i
-
1
validates :brand_website, presence: true, format:{ with: VALID_URL_REGEX, message: "is not valid url"}
-
# validates :brand_name_arabic, presence: true
-
1
has_one_attached :brand_image, dependent: :destroy
-
-
1
YEARS = (1900..Date.current.year).to_a.freeze
-
1
validates :brand_year, inclusion: { in: YEARS, allow_blank: true }
-
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue"
-
1
has_many :restricted_brands, class_name: "BxBlockCatalogue::RestrictedBrand", dependent: :destroy
-
1
has_one :store, class_name: "BxBlockStoreManagement::Store", dependent: :destroy
-
1
has_many :gated_brands, class_name: "BxBlockCatalogue::GatedBrand", dependent: :destroy
-
1
has_one :top_brand, class_name: "BxBlockDashboard::TopBrand", dependent: :destroy
-
1
has_many :parent_catalogues, class_name: "BxBlockCatalogue::ParentCatalogue"
-
1
before_destroy :check_for_associations
-
1
before_save :strip_whitespace
-
1
after_update :send_email_for_brand_approval, if: :approved_now?
-
1
private
-
-
1
def strip_whitespace
-
1853
self.brand_name = brand_name.strip if brand_name.present?
-
end
-
-
1
def check_for_associations
-
5
if catalogues.exists? || store.present?
-
3
errors.add(:base, "Cannot delete brand because it is associated with products or store.")
-
end
-
end
-
-
1
def approved_now?
-
10
saved_change_to_approve? && approve
-
end
-
-
1
def send_email_for_brand_approval
-
2
@account = self.account
-
2
BxBlockCatalogue::BrandApprovalMailer
-
.with(account: @account)
-
.brand_approval_email.deliver_now
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Catalogue < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :catalogues
-
-
1
belongs_to :category,
-
class_name: 'BxBlockCategories::Category',
-
foreign_key: 'category_id'
-
# // this clone product for variants(using self join)
-
1
has_many :variant_products, class_name: 'BxBlockCatalogue::Catalogue', foreign_key: 'parent_product_id',
-
inverse_of: :parent_product, dependent: :destroy
-
1
belongs_to :parent_product, class_name: 'BxBlockCatalogue::Catalogue', optional: true,
-
foreign_key: 'parent_product_id', inverse_of: :variant_products
-
-
# // parent catalogue not using so making it optional instead of removing
-
1
belongs_to :parent_catalogue, class_name: 'BxBlockCatalogue::ParentCatalogue', optional: true
-
1
belongs_to :sub_category, class_name: 'BxBlockCategories::SubCategory', optional: true
-
1
belongs_to :mini_category, class_name: 'BxBlockCategories::MiniCategory', optional: true
-
1
belongs_to :micro_category, class_name: 'BxBlockCategories::MicroCategory', optional: true
-
-
1
belongs_to :brand, class_name: 'BxBlockCatalogue::Brand', foreign_key: 'brand_id'
-
1
has_many :warehouse_catalogues, class_name: 'BxBlockCatalogue::WarehouseCatalogue', dependent: :destroy
-
1
has_many :warehouses, through: :warehouse_catalogues
-
-
1
validates :sku, presence: true,
-
format: { with: %r{\A(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9!@#$%^&*()_+-={}\[\]:;"'<>,.?/\\|`~\s]*\z}, message: 'should be alphanumeric and special characters' }
-
1345
validates :sku, uniqueness: { scope: :parent_product_id }, if: -> { parent_product_id.nil? }
-
1345
validates :sku, presence: true, if: -> { is_variant? }
-
1
validates :recommended_priority, allow_blank: true,
-
inclusion: { in: 0..9, message: 'must be between 0(low) and 9(high)' }
-
# validates :besku, presence: true
-
1
has_one :barcode, class_name: 'BxBlockCatalogue::Barcode', dependent: :destroy
-
1
has_one :catalogue_offer, class_name: 'BxBlockCatalogue::CatalogueOffer', dependent: :destroy
-
1
has_many :deal_catalogues, class_name: 'BxBlockCatalogue::DealCatalogue', dependent: :destroy
-
1
has_many :deals, through: :deal_catalogues, class_name: 'BxBlockCatalogue::Deal'
-
-
1
has_many :catalogue_contents, class_name: 'BxBlockCatalogue::CatalogueContent', dependent: :destroy
-
-
1
has_many :custom_fields, through: :catalogue_contents, class_name: 'BxBlockCategories::CustomField'
-
-
1
has_one :product_content, class_name: 'BxBlockCatalogue::ProductContent', dependent: :destroy
-
1
accepts_nested_attributes_for :catalogue_contents, :product_content, allow_destroy: true
-
-
1
has_and_belongs_to_many :store_menus, join_table: 'catalogues_store_menus',
-
class_name: 'BxBlockStoreManagement::StoreMenu', optional: true
-
-
1
has_many :review_and_ratings, class_name: 'BxBlockCatalogue::Review', dependent: :destroy
-
# // this object is for variant product's variant attributes and values
-
1
has_one :product_variant_group, class_name: 'BxBlockCatalogue::ProductVariantGroup',
-
foreign_key: 'variant_product_id', dependent: :destroy
-
# // this model is for variant attributes and values
-
1
has_many :product_variant_groups, class_name: 'BxBlockCatalogue::ProductVariantGroup', dependent: :destroy
-
# // this model is for group of attributes and values for variants
-
1
has_many :catalogue_variants, through: :product_variant_groups, class_name: 'BxBlockCatalogue::CatalogueVariant'
-
1
has_many :favourites, as: :favouriteable, class_name: 'BxBlockFavourites::Favourite', dependent: :destroy
-
1
has_many :order_items, class_name: 'BxBlockShoppingCart::OrderItem', dependent: :destroy
-
1
has_many :orders, through: :order_items, class_name: 'BxBlockShoppingCart::Order'
-
-
1
has_one_attached :product_image, dependent: :destroy
-
# validates :product_image, presence: true
-
1
validate :validate_image_type
-
-
1
has_many :subscribe_coupons, class_name: 'BxBlockCouponCg::SubscribeCoupon', dependent: :destroy
-
1
has_many :coupon_codes, through: :subscribe_coupons, class_name: 'BxBlockCouponCg::CouponCode', source: :coupon
-
1
belongs_to :seller, class_name: 'AccountBlock::Account', optional: true
-
1
has_many :trending_product_selections, class_name: 'BxBlockDashboard::TrendingProductSelection', dependent: :destroy
-
1
has_many :favorite_book_catalogues, class_name: 'BxBlockDashboard::AuthorFavoriteBookCatalogue', dependent: :destroy
-
1
has_many :banners, class_name: 'BxBlockDashboard::Banner', dependent: :destroy
-
-
1
has_many :wms_product_infos, class_name: 'BxBlockOrderManagement::WmsProductInfo', dependent: :destroy
-
1
has_many :wms_consignment_orders, class_name: 'BxBlockOrderManagement::WmsConsignmentOrder', dependent: :destroy
-
1
has_many :product_views, class_name: 'BxBlockSalesreporting::ProductView', dependent: :destroy
-
-
1
before_save :assign_besku_if_not_exist
-
-
1
before_save :validate_product_title
-
1
before_save :set_default_content_status, if: :new_record?
-
1
before_save :set_default_fulfillment, if: :new_record?
-
1
before_save :archived_status_change
-
1324
before_save :update_final_price, if: -> { persisted? }
-
-
1
after_save :create_catalogue_contents
-
1
after_save :product_status_change_notification
-
-
1
scope :low_to_high, -> { order(final_price: :asc) }
-
1
scope :high_to_low, -> { order(final_price: :desc) }
-
1
scope :product_title_AZ, -> { joins(:product_content).order('product_contents.product_title ASC') }
-
1
scope :product_title_ZA, -> { joins(:product_content).order('product_contents.product_title DESC') }
-
15
scope :whats_new, -> { order(created_at: :desc) }
-
2
scope :recommended, -> { order(recommended_priority: :desc) }
-
2
scope :popularity, -> { order(purchased_count: :desc) }
-
-
1
def update_total_stocks
-
9
total_stocks = warehouse_catalogues.sum(:stocks)
-
9
update!(stocks: total_stocks)
-
end
-
-
1
def is_variant?
-
1911
is_variant
-
end
-
-
1
def update_final_price
-
327
self.final_price = calculate_effective_price
-
327
self.offer_percentage = calculate_offer_percentage
-
327
self.stroked_price = calculate_stroked_price
-
end
-
-
1
def calculate_effective_price
-
1282
retail_price = product_content&.retail_price&.to_f || 0.0
-
1282
return catalogue_offer.sale_price.to_f if catalogue_offer&.active? && catalogue_offer.sale_price.present?
-
1276
active_deal = deal_catalogues.where(status: 'approved').last
-
1276
deal = fetch_active_deal(active_deal)
-
1276
if active_deal.present? && deal&.active?
-
136
return active_deal.deal_price.to_f if active_deal.deal.discount_type == 'flat'
-
121
discount = (retail_price * active_deal.deal.discount_value / 100.0).round(2)
-
121
discount = [discount, active_deal.deal_price].min
-
121
return (retail_price - discount).round(2)
-
end
-
1140
retail_price || 0.0
-
end
-
-
1
def fetch_active_deal(active_deal)
-
2299
active_deal.deal if active_deal.present?
-
end
-
-
1
def calculate_stroked_price
-
1023
mrp = product_content&.mrp&.to_f
-
1023
retail_price = product_content&.retail_price&.to_f || 0.0
-
-
1023
active_deal = deal_catalogues.where(status: 'approved').last
-
1023
deal = fetch_active_deal(active_deal)
-
-
1023
return retail_price if catalogue_offer&.active? || active_deal.present? || deal&.active?
-
-
910
return retail_price
-
-
mrp || 0.0
-
end
-
-
1
def calculate_offer_percentage
-
1023
if catalogue_offer&.active? || deal_catalogues.where(status: 'approved').exists?
-
113
retail_price = product_content&.retail_price&.to_f || 0.0
-
113
return 0.0 if retail_price.zero? || final_price.blank?
-
-
86
return ((retail_price - final_price) / retail_price * 100).round(2)
-
end
-
-
910
0.0
-
end
-
-
1
private
-
-
1
def archived_status_change
-
1323
self.status = false if content_status == 'archived'
-
end
-
-
1
def validate_product_title
-
1323
return if product_content.blank? || product_content.product_title.blank?
-
-
292
self.product_title = product_content.product_title
-
end
-
-
1
def validate_image_type
-
1342
allowed_types = %w[image/jpeg image/jpg image/png image/webp]
-
-
1342
return unless product_image.attached? && !product_image.content_type.in?(allowed_types)
-
-
1
errors.add(:product_image, 'must be a JPEG/JPG/PNG/WebP file')
-
end
-
-
1
def assign_besku_if_not_exist
-
1323
self.besku = generate_unique_besku(:besku) if besku.blank?
-
1323
self.bibc = generate_unique_besku(:bibc) if bibc.blank?
-
end
-
-
1
def generate_unique_besku(field)
-
9
gen_besku = nil
-
9
loop do
-
9
gen_besku = SecureRandom.hex(8).upcase
-
9
unless Catalogue.exists?(field => gen_besku) && ProductVariantGroup.exists?("product_#{field}".to_sym => gen_besku)
-
9
break
-
end
-
end
-
9
gen_besku
-
end
-
-
1
def set_default_content_status
-
996
self.content_status ||= 'under_review'
-
end
-
-
1
def set_default_fulfillment
-
996
self.fulfilled_type ||= 'partner'
-
end
-
-
1
def create_catalogue_contents
-
1323
custom_fields = []
-
-
1323
custom_fields += category.custom_fields if category
-
1323
custom_fields += sub_category.custom_fields if sub_category.present?
-
1323
custom_fields += mini_category.custom_fields if mini_category.present?
-
1323
custom_fields += micro_category.custom_fields if micro_category.present?
-
-
1323
catalogue_contents.where.not(custom_field_id: custom_fields.map(&:id)).destroy_all
-
1323
return unless custom_fields.present?
-
-
397
custom_fields.each do |custom_field|
-
462
content = catalogue_contents.find_or_create_by(custom_field_id: custom_field.id)
-
462
if content.custom_field_name != custom_field.field_name
-
304
content.update(custom_field_name: custom_field.field_name)
-
end
-
end
-
end
-
-
1
def product_status_change_notification
-
1323
if (saved_change_to_content_status? || saved_change_to_status?) && content_status == 'accepted' && status == true
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(product: self, account: seller, subject: 'Product Successfully Added', file: 'product_added_notification')
-
.notification.deliver_now
-
1322
elsif saved_change_to_content_status? && content_status == 'rejected'
-
1
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(product: self, account: seller, subject: 'Product Listing Failed', file: 'product_failure_notification')
-
.notification.deliver_now
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueContent < ApplicationRecord
-
1
self.table_name = :catalogue_contents
-
1
belongs_to :custom_field, class_name: "BxBlockCategories::CustomField", optional: true
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
validates :value, allow_blank: true, length: { in: 3..30 }
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueOffer < ApplicationRecord
-
1
self.table_name = :catalogue_offers
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :barcode, class_name: "BxBlockCatalogue::Barcode", foreign_key: "barcode_id", optional: true
-
45
validate :validate_exist_deals, if: -> { status }
-
-
1
after_save :update_catalogue_final_price
-
1
after_destroy :update_catalogue_final_price
-
-
1
after_save :update_deal_seller_price, if: :saved_change_to_sale_price?
-
-
44
after_commit :schedule_expiry_job, if: -> { active? }
-
-
1
def active?
-
216
status && sale_schedule_to.present? && sale_schedule_to >= Date.today && sale_schedule_from <= Date.today
-
end
-
-
1
def update_catalogue_final_price
-
43
catalogue.update_columns(
-
final_price: catalogue.calculate_effective_price,
-
offer_percentage: catalogue.calculate_offer_percentage,
-
stroked_price: catalogue.calculate_stroked_price
-
43
) if catalogue.present?
-
end
-
-
1
private
-
-
1
def schedule_expiry_job
-
5
ExpireOffersAndDealsJob.set(wait_until: sale_schedule_to.to_time).perform_later
-
end
-
-
1
def update_deal_seller_price
-
38
return unless catalogue.deal_catalogues.present?
-
-
2
catalogue.deal_catalogues.update_all(seller_price: sale_price)
-
end
-
-
1
def validate_exist_deals
-
10
if catalogue.deal_catalogues.where(status: [:review, :approved]).any? { |deal_cat| deal_cat.deal.active? }
-
1
errors.add(:catalogue, "Cannot create an active offer as there is an active and approved deal for this product.")
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueVariant < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :catalogue_variants
-
-
# belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :micro_category, class_name: "BxBlockCategories::MicroCategory"
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
1
has_many :variant_attributes, class_name: "BxBlockCatalogue::VariantAttribute", dependent: :destroy
-
1
has_many :product_variant_groups,class_name: "BxBlockCatalogue::ProductVariantGroup"
-
1
accepts_nested_attributes_for :variant_attributes, allow_destroy: true
-
-
1
validates :group_name, presence: true, uniqueness: { scope: :seller_id }
-
-
1
before_destroy :check_product_variant_groups
-
-
1
private
-
-
1
def check_product_variant_groups
-
2
if product_variant_groups.exists?
-
1
errors.add(:base, "Selected group has variants linked to it. Please review and delete the variants to delete the group.")
-
1
throw :abort
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Deal < ApplicationRecord
-
1
self.table_name = :deals
-
1
enum discount_type: {
-
percentage: 'percentage',
-
flat: 'flat'
-
}
-
1
validates :deal_name, presence: true, length: { maximum: 50 }
-
1
validates :deal_code, presence: true, length: { maximum: 50 }
-
1
validates :start_date,:end_date,:discount_type, presence: true
-
1
validate :end_date_must_be_after_start_date
-
1
validate :start_date_must_be_after_today
-
1
has_many :deal_catalogues, class_name: "BxBlockCatalogue::DealCatalogue", dependent: :destroy
-
1
has_many :catalogues, through: :deal_catalogues, class_name: "BxBlockCatalogue::Deal"
-
1
has_many :banners, class_name: "BxBlockDashboard::Banner", dependent: :destroy
-
1
has_many :weekly_deals, class_name: "BxBlockDashboard::WeeklyDeal", dependent: :destroy
-
1
validates :discount_value, presence: true, numericality: { greater_than_or_equal_to: 0 }
-
1
after_save :update_deal_catalogue_statuses, if: :saved_change_to_status?
-
141
after_commit :schedule_expiry_job, if: -> { active? }
-
47
scope :active_deals, -> { where("end_date >= ? AND status != ?", Date.today, false) }
-
-
-
1
def active?
-
406
end_date >= Date.today && status
-
end
-
-
1
private
-
-
1
def schedule_expiry_job
-
134
ExpireOffersAndDealsJob.set(wait_until: end_date.to_time).perform_later
-
end
-
-
1
def start_date_must_be_after_today
-
137
if start_date.present? && start_date < Date.today
-
errors.add(:start_date, 'must be today or after today')
-
end
-
end
-
-
1
def end_date_must_be_after_start_date
-
137
return if start_date.blank? || end_date.blank?
-
-
137
if end_date < start_date
-
1
errors.add(:end_date, "must be after the start date")
-
end
-
end
-
-
1
def update_deal_catalogue_statuses
-
139
if saved_change_to_status? && !status
-
3
deal_catalogues.update_all(status: :expired)
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class DealCatalogue < ApplicationRecord
-
1
self.table_name = :deal_catalogues
-
1
belongs_to :deal, class_name: "BxBlockCatalogue::Deal"
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
-
207
validates :deal_price, presence: true, numericality: { greater_than_or_equal_to: 0 }, if: -> { deal&.discount_type == "flat" }
-
-
1
enum status: { review: 0, approved: 1, rejected: 2, expired: 3 }
-
1
before_create :set_deal_price_and_offer_price
-
-
1
before_save :update_catalogue_details
-
-
5
before_update :set_deal_price_and_offer_price, unless: -> { deal_price_changed? }
-
-
1
validate :deal_exists_and_approved_or_review, unless: :can_be_updated?
-
-
1
after_save :update_catalogue_final_price
-
1
after_destroy :update_catalogue_final_price
-
-
1
def update_catalogue_final_price
-
100
catalogue.update_columns(
-
final_price: catalogue.calculate_effective_price,
-
offer_percentage: catalogue.calculate_offer_percentage,
-
stroked_price: catalogue.calculate_stroked_price
-
100
) if catalogue.present?
-
end
-
-
1
attr_accessor :skip_deal_price_callback
-
-
1
private
-
-
1
def can_be_updated?
-
102
expired? || rejected?
-
end
-
-
1
def deal_exists_and_approved_or_review
-
100
if catalogue
-
99
existing_deal_catalogues = catalogue.deal_catalogues.where.not(id: id).where(status: [:review, :approved])
-
-
101
deal_active = existing_deal_catalogues.any? { |deal_cat| deal_cat.deal.active? }
-
-
99
offer_active = catalogue.catalogue_offer&.active?
-
-
99
if deal_active || offer_active
-
2
errors.add(:catalogue, "A deal for this product already exists and is either in review, approved, or there is an active offer.")
-
end
-
end
-
end
-
-
1
def update_catalogue_details
-
99
catalogue = self.catalogue
-
-
99
self.seller_sku = catalogue.is_variant ? catalogue.product_variant_group&.product_sku : catalogue.sku
-
99
self.product_title = catalogue.product_content&.product_title
-
99
self.seller_price = catalogue.product_content&.retail_price
-
99
self.current_offer_price = catalogue.catalogue_offer&.sale_price || 0.0
-
end
-
-
1
def set_deal_price_and_offer_price
-
96
if deal.active? && deal.discount_value.present?
-
93
if deal.discount_type == "flat"
-
11
set_deal_price
-
-
82
elsif deal.discount_type == "percentage"
-
82
set_current_offer_price
-
else
-
nil
-
end
-
end
-
end
-
-
1
def set_current_offer_price
-
82
cprice = catalogue.product_content&.retail_price || 0.0
-
82
percentage_discount = deal.discount_value.to_f / 100.0
-
82
discount_amount = cprice * percentage_discount
-
82
price = cprice - discount_amount
-
82
self.deal_price = price
-
end
-
-
1
def set_deal_price
-
11
dprice = catalogue.product_content&.retail_price || 0.0
-
11
discounted_price = (dprice - deal.discount_value).round(2)
-
11
self.deal_price = [discounted_price, 0.0].max
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class FeatureBullet < ApplicationRecord
-
1
self.table_name = :feature_bullets
-
-
1
belongs_to :product_content, class_name: "BxBlockCatalogue::ProductContent"
-
-
1
validates :value, presence:true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class GatedBrand < ApplicationRecord
-
1
self.table_name = :gated_brands
-
1
belongs_to :brand, class_name: "BxBlockCatalogue::Brand"
-
-
1
has_one_attached :reseller_permit_document, dependent: :destroy
-
-
end
-
end
-
-
1
module BxBlockCatalogue
-
1
class GroupAttribute < ApplicationRecord
-
1
self.table_name = :group_attributes
-
1
belongs_to :product_variant_group, class_name: "BxBlockCatalogue::ProductVariantGroup"
-
1
has_one :catalogue, through: :product_variant_group, class_name: "BxBlockCatalogue::Catalogue"
-
-
1
belongs_to :variant_attribute, class_name: "BxBlockCatalogue::VariantAttribute", optional: true
-
1
belongs_to :attribute_option, class_name: "BxBlockCatalogue::AttributeOption", optional: true
-
-
1
validates :attribute_name, :option, presence: true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class HelpfulReview < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :helpful_reviews
-
-
1
belongs_to :review, class_name: "BxBlockCatalogue::Review"
-
1
belongs_to :customer, class_name: "AccountBlock::Account"
-
-
1
validates :review_id, uniqueness: { scope: :customer_id, message: 'You have already marked this review as helpful' }
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ImageUrl < ApplicationRecord
-
1
self.table_name = :image_urls
-
-
1
belongs_to :product_content, class_name: "BxBlockCatalogue::ProductContent"
-
-
1
validates :url, presence: true, format: { with: /\A(?:https:\/\/|www\.)[^\s]+\z/, message: "should start with 'https://' or 'www.'" }
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ParentCatalogue < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :parent_catalogues
-
-
1
belongs_to :category,
-
class_name: "BxBlockCategories::Category",
-
foreign_key: "category_id"
-
1
belongs_to :brand, class_name: "BxBlockCatalogue::Brand", foreign_key: "brand_id"
-
1
belongs_to :sub_category, class_name: "BxBlockCategories::SubCategory", optional: true
-
1
belongs_to :mini_category, class_name: "BxBlockCategories::MiniCategory", optional: true
-
1
belongs_to :micro_category, class_name: "BxBlockCategories::MicroCategory", optional: true
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue", dependent: :nullify
-
-
1
validates :besku, uniqueness: true
-
1
has_one_attached :product_image, dependent: :destroy
-
1
validates :product_title, length: { in: 5..35 }
-
# validates :prod_model_no, format: { with: /\A[A-Z0-9]+\z/, message: "should be uppercase alphanumeric" }, length: { in: 5..13, allow_blank: true }
-
1
validate :custom_prod_model_no_validation
-
-
1
before_create :generate_unique_besku
-
1
validate :validate_image_type
-
-
# has_one :barcode, class_name: "BxBlockCatalogue::Barcode", dependent: :destroy
-
# has_one :catalogue_offer, class_name: "BxBlockCatalogue::CatalogueOffer", dependent: :destroy
-
# has_many :deal_catalogues, class_name: "BxBlockCatalogue::DealCatalogue", dependent: :destroy
-
# has_many :deals, through: :deal_catalogues, class_name: "BxBlockCatalogue::Deal"
-
-
-
# has_one :product_content, class_name: "BxBlockCatalogue::ProductContent", dependent: :destroy
-
-
-
# has_many :review_and_ratings, class_name: "BxBlockCatalogue::Review", dependent: :destroy
-
# has_many :catalogue_variants, class_name: "BxBlockCatalogue::CatalogueVariant", dependent: :destroy
-
# has_many :product_variant_groups, class_name: "BxBlockCatalogue::ProductVariantGroup", dependent: :destroy
-
# has_many :favourites, as: :favouriteable, class_name: "BxBlockFavourites::Favourite", dependent: :destroy
-
# has_many :order_items, class_name: 'BxBlockShoppingCart::OrderItem', dependent: :destroy
-
# has_many :orders, through: :order_items, class_name: 'BxBlockShoppingCart::Order'
-
-
-
# has_many :subscribe_coupons, class_name: "BxBlockCouponCg::SubscribeCoupon", dependent: :destroy
-
# has_many :coupon_codes, through: :subscribe_coupons, class_name: "BxBlockCouponCg::CouponCode", source: :coupon
-
# belongs_to :seller, class_name: "AccountBlock::Account", optional: true
-
-
# validates :sku, presence: true, uniqueness: true
-
# has_many :catalogue_contents, class_name: "BxBlockCatalogue::CatalogueContent", dependent: :destroy
-
# accepts_nested_attributes_for :catalogue_contents
-
-
# has_many :custom_fields, through: :catalogue_contents, class_name: "BxBlockCategories::CustomField"
-
-
-
# has_and_belongs_to_many :store_menus, join_table: 'catalogues_store_menus', class_name: "BxBlockStoreManagement::StoreMenu", optional: true
-
-
# accepts_nested_attributes_for :catalogue_variants, allow_destroy: true
-
-
1
def generate_unique_besku
-
988
self.besku = SecureRandom.hex(8).upcase
-
end
-
-
1
private
-
-
1
def validate_image_type
-
987
allowed_types = %w(image/jpeg image/jpg image/png image/webp)
-
-
987
if product_image.attached? && !product_image.content_type.in?(allowed_types)
-
errors.add(:product_image, 'must be a JPEG/JPG/PNG/WebP file')
-
end
-
end
-
-
1
def custom_prod_model_no_validation
-
987
if prod_model_no.present?
-
987
unless prod_model_no.match?(/\A[A-Z0-9]+\z/)
-
errors.add(:prod_model_no, "should be uppercase alphanumeric")
-
end
-
-
987
unless (5..13).cover?(prod_model_no.length)
-
errors.add(:prod_model_no, "length should be between 5 and 13 characters")
-
end
-
end
-
end
-
-
end
-
end
-
# // This model also for the content tab of product, added because change in functionality, also there is another model catalogue content which created before this and its becasue of custom fields, if needed we can use
-
1
module BxBlockCatalogue
-
1
class ProductContent < ApplicationRecord
-
1
self.table_name = :product_contents
-
-
1
PRODUCT_COLORS = ["Purple", "Light Coral","Lime Green", "Yellow", "Grey", "Ocean Green", "Pink", "Sky blue"]
-
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
has_one :size_and_capacity, class_name: "BxBlockCatalogue::SizeAndCapacity", dependent: :destroy
-
1
has_one :shipping_detail, class_name: "BxBlockCatalogue::ShippingDetail", dependent: :destroy
-
1
has_many :image_urls, class_name: "BxBlockCatalogue::ImageUrl", dependent: :destroy
-
1
has_many :feature_bullets, class_name: "BxBlockCatalogue::FeatureBullet", dependent: :destroy
-
1
has_many :special_features, class_name: "BxBlockCatalogue::SpecialFeature", dependent: :destroy
-
1
accepts_nested_attributes_for :feature_bullets, :image_urls, :special_features, :shipping_detail, :size_and_capacity, allow_destroy: true
-
1
validates :mrp, :retail_price, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
-
1
validates :brand_name, :product_title, :retail_price, :whats_in_the_package, :country_of_origin, :long_description,:product_color, presence: true
-
1145
validates :unique_psku, presence: true, uniqueness: { scope: :catalogue_id }, if: -> { catalogue&.parent_product_id.nil? }
-
573
validates :unique_psku, presence: true, if: -> { catalogue&.is_variant? }
-
1
validates :gtin, length: { in: 8..14 }, numericality: { only_integer: true }, uniqueness: true, allow_blank: true
-
1
validates :warranty_days, :warranty_months, numericality: { only_integer: true, less_than_or_equal_to: 999, message: "must be integer and no more than 3 digits" }, allow_nil: true
-
1
validate :validate_matching_sku
-
1
validate :validate_presence_of_feature_bullets_and_image_urls
-
569
validate :validate_country_of_origin, if: -> { country_of_origin.present? }
-
569
validate :validate_product_color, if: -> { product_color.present? }
-
-
1
before_save :update_product_title
-
1
after_save :update_deal_seller_price, if: :saved_change_to_retail_price?
-
-
1
private
-
-
1
def update_deal_seller_price
-
278
return unless catalogue.deal_catalogues.present?
-
-
4
catalogue.deal_catalogues.update_all(seller_price: retail_price)
-
end
-
-
1
def validate_country_of_origin
-
565
countries_name = CS.countries.values.map(&:downcase)
-
565
unless countries_name.include?(country_of_origin.downcase)
-
errors.add(:country_of_origin, "is not a valid country")
-
end
-
end
-
-
1
def validate_product_color
-
566
product_colors = PRODUCT_COLORS.map(&:downcase)
-
566
unless product_colors.include?(product_color.downcase)
-
1
errors.add(:product_color, "is not a valid product color")
-
end
-
end
-
-
1
def validate_presence_of_feature_bullets_and_image_urls
-
568
if feature_bullets.empty?
-
3
errors.add(:feature_bullets, "At least one feature bullet must be present")
-
end
-
-
568
if image_urls.empty?
-
2
errors.add(:image_urls, "At least one image URL must be present")
-
end
-
end
-
-
1
def validate_matching_sku
-
568
unless catalogue && unique_psku == catalogue.sku
-
3
errors.add(:unique_psku, "must match the SKU of the associated catalogue")
-
end
-
end
-
-
1
def update_product_title
-
551
if catalogue&.product_title.present? && product_title.blank?
-
self.product_title = catalogue.product_title
-
551
elsif catalogue.present? && catalogue.product_title != product_title
-
269
catalogue.update(product_title: product_title)
-
end
-
-
# added for price update
-
551
catalogue.update_columns(
-
final_price: catalogue.calculate_effective_price,
-
offer_percentage: catalogue.calculate_offer_percentage,
-
stroked_price: catalogue.calculate_stroked_price
-
551
) if catalogue.present?
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ProductVariantGroup < ApplicationRecord
-
1
self.table_name = :product_variant_groups
-
1
belongs_to :catalogue_variant, class_name: "BxBlockCatalogue::CatalogueVariant", optional: true, foreign_key: "catalogue_variant_id"
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :variant_product, class_name: "BxBlockCatalogue::Catalogue", optional: true, foreign_key: "variant_product_id", dependent: :destroy
-
1
has_many :group_attributes, class_name: "BxBlockCatalogue::GroupAttribute", dependent: :destroy
-
1
has_many :order_items, class_name: "BxBlockShoppingCart::OrderItem", dependent: :destroy
-
1
has_many :favourites, class_name: "BxBlockFavourites::Favourite", dependent: :destroy
-
1
has_many :warehouse_catalogues, class_name: "BxBlockCatalogue::WarehouseCatalogue", dependent: :destroy
-
1
has_many :warehouses, through: :warehouse_catalogues
-
-
1
accepts_nested_attributes_for :group_attributes, allow_destroy: true
-
-
1
has_many_attached :product_images, dependent: :destroy
-
1
validates :product_sku, presence: true
-
1
validate :unique_product_sku_across_catalogues_and_groups
-
1
before_save :create_besku
-
-
1
def create_and_associate_variant_product
-
3
BxBlockCatalogue::Catalogue.transaction do
-
3
variant_product = BxBlockCatalogue::Catalogue.new(
-
catalogue_attributes.merge(
-
parent_product: catalogue,
-
is_variant: true,
-
product_content_attributes: product_content_attributes
-
)
-
)
-
-
3
if catalogue.product_image.attached?
-
3
variant_product.product_image.attach(catalogue.product_image.blob)
-
end
-
-
3
variant_product.save!
-
3
Rails.logger.debug("Variant product created: #{variant_product.inspect}")
-
-
3
update!(variant_product: variant_product)
-
3
Rails.logger.debug("ProductVariantGroup updated with variant_product: #{variant_product.inspect}")
-
end
-
rescue StandardError => e
-
Rails.logger.error("Error creating and associating variant product: #{e.message}")
-
raise e
-
end
-
-
1
def catalogue_attributes
-
3
catalogue.attributes.except("id", "created_at", "updated_at", "is_variant", "purchased_count", "stocks", "status", "content_status", "parent_catalogue_id")
-
end
-
-
1
def product_content_attributes
-
3
return {} unless catalogue.product_content
-
-
3
product_content_attr = catalogue.product_content.attributes.except("id", "catalogue_id", "created_at", "updated_at", "gtin")
-
3
product_content_attr.merge!(
-
size_and_capacity_attributes: size_and_capacity_attributes,
-
shipping_detail_attributes: shipping_detail_attributes,
-
image_urls_attributes: image_urls_attributes,
-
feature_bullets_attributes: feature_bullets_attributes
-
)
-
end
-
-
1
def size_and_capacity_attributes
-
3
return {} unless catalogue.product_content&.size_and_capacity
-
-
1
catalogue.product_content.size_and_capacity.attributes.except("id", "product_content_id", "created_at", "updated_at")
-
end
-
-
1
def shipping_detail_attributes
-
3
return {} unless catalogue.product_content&.shipping_detail
-
-
1
catalogue.product_content.shipping_detail.attributes.except("id", "product_content_id", "created_at", "updated_at")
-
end
-
-
1
def image_urls_attributes
-
3
return [] unless catalogue.product_content&.image_urls
-
-
7
catalogue.product_content.image_urls.map { |image_url| image_url.attributes.except("id", "product_content_id", "created_at", "updated_at") }
-
end
-
-
1
def feature_bullets_attributes
-
3
return [] unless catalogue.product_content&.feature_bullets
-
-
7
catalogue.product_content.feature_bullets.map { |bullet| bullet.attributes.except("id", "product_content_id", "created_at", "updated_at") }
-
end
-
-
1
private
-
-
1
def unique_product_sku_across_catalogues_and_groups
-
# if new_record? || product_sku_changed?
-
79
if BxBlockCatalogue::ProductVariantGroup.where.not(id: id).exists?(product_sku: product_sku) ||
-
BxBlockCatalogue::Catalogue.exists?(sku: product_sku)
-
1
errors.add(:product_sku, "must be unique across catalogues and product variant groups")
-
end
-
# end
-
end
-
-
1
def create_besku
-
75
self.product_besku = generate_unique_besku(:besku) unless product_besku.present?
-
75
self.product_bibc = generate_unique_besku(:bibc) unless product_bibc.present?
-
end
-
-
1
def generate_unique_besku(field)
-
71
gen_besku = nil
-
71
loop do
-
71
gen_besku = SecureRandom.hex(8).upcase
-
71
break unless Catalogue.exists?(field => gen_besku) && ProductVariantGroup.exists?("product_#{field}".to_sym => gen_besku)
-
end
-
71
gen_besku
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class RestrictedBrand < ApplicationRecord
-
1
self.table_name = :restricted_brands
-
1
belongs_to :brand, class_name: "BxBlockCatalogue::Brand"
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
-
1
has_one_attached :reseller_permit_document
-
-
1
validates :reseller_permit_document ,presence: true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Review < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :review_and_ratings
-
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :account, foreign_key: :reviewer_id, class_name: "AccountBlock::Account"
-
# adding optional to not produce error after merge
-
1
belongs_to :order_item, class_name: 'BxBlockShoppingCart::OrderItem', optional: true
-
-
1
validates_presence_of :reviewer_id, :catalogue_id, :rating
-
1
validates :rating, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 5 }
-
# validate :check_existing_approved_review, on: [:create, :update]
-
1
has_many_attached :review_images, dependent: :destory
-
1
validate :validate_review_images
-
-
1
has_many :helpful_reviews, class_name: "BxBlockCatalogue::HelpfulReview", dependent: :destroy
-
1
has_many :helpful_accounts, through: :helpful_reviews, class_name: "AccountBlock::Account", source: :account
-
1
accepts_nested_attributes_for :helpful_reviews, allow_destroy: true
-
-
#approved reviews
-
647
scope :approved_reviews, -> { where(is_approved: true) }
-
2
scope :seller_reviews, -> { where(review_type: 'seller') }
-
-
1
def helpful_count
-
18
helpful_reviews.count
-
end
-
-
1
def helpful_by?(customer)
-
4
helpful_reviews.exists?(customer_id: customer.id)
-
end
-
-
1
private
-
-
1
def validate_review_images
-
402
return unless review_images.attached?
-
-
15
review_images.each do |image|
-
15
if !image.content_type.in?(%w[image/png image/jpg image/jpeg]) || image.blob.byte_size > 5.megabytes
-
1
errors.add(:review, 'Failed to upload image. only png, jpg, jpeg format is allowed and maximum size is 5mb')
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ShippingDetail < ApplicationRecord
-
1
self.table_name = :shipping_details
-
-
1
SHIPPING_UNITS = ['Kilogram','Gram','Ounce (OZ)','pound (lb)','Centimeter','Meter','Inch','Feet'].freeze
-
-
1
belongs_to :product_content, class_name: "BxBlockCatalogue::ProductContent"
-
1
validates :shipping_length, :shipping_height, :shipping_width, :shipping_weight, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
-
1
validate :validate_unit
-
1
validate :validate_shipping_length_and_unit
-
1
validate :validate_shipping_height_and_unit
-
1
validate :validate_shipping_width_and_unit
-
1
validate :validate_shipping_weight_and_unit
-
-
1
private
-
-
1
def validate_unit
-
20
shipping_units = SHIPPING_UNITS.map(&:downcase)
-
20
error_message = "is not valid. It must be one of: #{SHIPPING_UNITS.join(', ')}"
-
20
if shipping_length_unit.present? && !shipping_units.include?(shipping_length_unit.downcase)
-
1
errors.add(:shipping_length_unit, error_message)
-
end
-
-
20
if shipping_height_unit.present? && !shipping_units.include?(shipping_height_unit.downcase)
-
1
errors.add(:shipping_height_unit, error_message)
-
end
-
-
20
if shipping_width_unit.present? && !shipping_units.include?(shipping_width_unit.downcase)
-
errors.add(:shipping_width_unit, error_message)
-
end
-
-
20
if shipping_weight_unit.present? && !shipping_units.include?(shipping_weight_unit.downcase)
-
errors.add(:shipping_weight_unit, error_message)
-
end
-
end
-
-
1
def validate_shipping_length_and_unit
-
20
if shipping_length.present? && shipping_length_unit.blank?
-
1
errors.add(:shipping_length_unit, "must be present if shipping_length is provided")
-
19
elsif shipping_length_unit.present? && shipping_length.blank?
-
errors.add(:shipping_length, "must be present if shipping_length_unit is provided")
-
else
-
19
true
-
end
-
end
-
-
1
def validate_shipping_height_and_unit
-
20
if shipping_height.present? && shipping_height_unit.blank?
-
errors.add(:shipping_height_unit, "must be present if shipping_height is provided")
-
20
elsif shipping_height_unit.present? && shipping_height.blank?
-
1
errors.add(:shipping_height, "must be present if shipping_height_unit is provided")
-
else
-
19
true
-
end
-
end
-
-
1
def validate_shipping_width_and_unit
-
20
if shipping_width.present? && shipping_width_unit.blank?
-
1
errors.add(:shipping_width_unit, "must be present if shipping_width is provided")
-
19
elsif shipping_width_unit.present? && shipping_width.blank?
-
errors.add(:shipping_width, "must be present if shipping_width_unit is provided")
-
else
-
19
true
-
end
-
end
-
-
1
def validate_shipping_weight_and_unit
-
20
if shipping_weight.present? && shipping_weight_unit.blank?
-
errors.add(:shipping_weight_unit, "must be present if shipping_weight is provided")
-
20
elsif shipping_weight_unit.present? && shipping_weight.blank?
-
1
errors.add(:shipping_weight, "must be present if shipping_weight_unit is provided")
-
else
-
19
true
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class SizeAndCapacity < ApplicationRecord
-
1
self.table_name = :size_and_capacities
-
-
1
SIZE_UNITS = ['Grams', 'Kilograms', 'Centimeter', 'Millimeter'].freeze
-
1
CAPACITY_UNITS = ['Litre', 'Millilitre'].freeze
-
-
1
belongs_to :product_content, class_name: "BxBlockCatalogue::ProductContent"
-
-
1
validates :size,:capacity,:number_of_pieces, allow_blank: true, numericality: { greater_than_or_equal_to: 0 }
-
1
validates :prod_model_number, allow_blank: true, format: { with: /\A[a-zA-Z0-9!@#$%^&*()_+-={}\[\]:;"'<>,.?\/\\|`~\s]{3,16}\z/, message: "must be alphanumeric, special characters and between 3 to 16 characters long" }
-
-
1
validates :hs_code, format: { with: /\A\d{6}\z/, message: "should be a 6-digit numeric code" }, unless: :hs_code_blank
-
1
validate :validate_unit
-
1
validate :validate_size_and_unit
-
1
validate :validate_capacity_and_unit
-
-
1
private
-
-
1
def validate_unit
-
20
size_units = SIZE_UNITS.map(&:downcase)
-
20
if size_unit.present? && !size_units.include?(size_unit.downcase)
-
errors.add(:size_unit, "is not valid. It must be one of: #{SIZE_UNITS.join(', ')}")
-
end
-
-
20
capacity_units = CAPACITY_UNITS.map(&:downcase)
-
20
if capacity_unit.present? && !capacity_units.include?(capacity_unit.downcase)
-
errors.add(:capacity_unit, "is not valid. It must be one of: #{CAPACITY_UNITS.join(', ')}")
-
end
-
end
-
-
1
def validate_size_and_unit
-
20
if size.present? && size_unit.blank?
-
1
errors.add(:size_unit, "must be present if size is provided")
-
19
elsif size_unit.present? && size.blank?
-
errors.add(:size, "must be present if size_unit is provided")
-
else
-
19
true
-
end
-
end
-
-
1
def validate_capacity_and_unit
-
20
if capacity.present? && capacity_unit.blank?
-
errors.add(:capacity_unit, "must be present if capacity is provided")
-
20
elsif capacity_unit.present? && capacity.blank?
-
1
errors.add(:capacity, "must be present if capacity_unit is provided")
-
else
-
19
true
-
end
-
end
-
-
1
def hs_code_blank
-
20
hs_code.blank?
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class SpecialFeature < ApplicationRecord
-
1
self.table_name = :special_features
-
-
1
belongs_to :product_content, class_name: "BxBlockCatalogue::ProductContent"
-
-
1
validates :value, presence:true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class VariantAttribute < ApplicationRecord
-
1
self.table_name = :variant_attributes
-
-
1
belongs_to :catalogue_variant, class_name: "BxBlockCatalogue::CatalogueVariant"
-
1
has_many :attribute_options, class_name: "BxBlockCatalogue::AttributeOption", dependent: :destroy
-
1
accepts_nested_attributes_for :attribute_options, allow_destroy: true
-
-
1
has_many :group_attributes, class_name: "BxBlockCatalogue::GroupAttribute", dependent: :destroy
-
1
validates :attribute_name, presence: true
-
-
1
before_save :update_group_attributes
-
-
1
private
-
-
1
def update_group_attributes
-
10
group_attributes.update_all(attribute_name: attribute_name) if attribute_name_changed?
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Warehouse < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :warehouses
-
1
validates :warehouse_name, presence: true
-
1
has_many :warehouse_catalogues, class_name: "BxBlockCatalogue::WarehouseCatalogue", dependent: :destroy
-
1
has_many :catalogues, through: :warehouse_catalogues
-
1
has_many :product_variant_groups, through: :warehouse_catalogues
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
has_many :delivery_request, class_name: 'BxBlockOrderManagement::DeliveryRequest', dependent: :destroy
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class WarehouseCatalogue < ApplicationRecord
-
1
self.table_name = :warehouse_catalogues
-
-
1
belongs_to :warehouse, class_name: "BxBlockCatalogue::Warehouse"
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :product_variant_group, class_name: "BxBlockCatalogue::ProductVariantGroup", optional: true
-
-
1
validate :unique_catalogue_and_variant_in_warehouse
-
# validate :unique_catalogue_in_warehouse
-
-
1
after_save :update_stocks_to_catalogue
-
-
1
private
-
-
1
def unique_catalogue_and_variant_in_warehouse
-
31
existing_record = BxBlockCatalogue::WarehouseCatalogue.find_by(warehouse_id: warehouse_id, catalogue_id: catalogue_id, product_variant_group_id: product_variant_group_id)
-
31
if existing_record && existing_record != self
-
1
errors.add(:base, "This catalogue is already exist in this warehouse")
-
end
-
end
-
-
1
def unique_catalogue_in_warehouse
-
existing_record = BxBlockCatalogue::WarehouseCatalogue.where(catalogue_id: catalogue_id, product_variant_group_id: product_variant_group_id).where.not(warehouse_id: warehouse_id).first
-
if existing_record
-
errors.add(:base, "This catalogue is already assigned to another warehouse")
-
end
-
end
-
-
1
def update_stocks_to_catalogue
-
29
catalogue.stocks = self.stocks
-
29
catalogue.save
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCategories
-
1
class Category < BxBlockCategories::ApplicationRecord
-
1
self.table_name = :categories
-
-
1
has_many :sub_categories, class_name: "BxBlockCategories::SubCategory", foreign_key: :parent_id, dependent: :destroy
-
1
has_many :mini_categories, through: :sub_categories, class_name: "BxBlockCategories::MiniCategory", source: :mini_categories, dependent: :destroy
-
1
has_many :micro_categories, through: :mini_categories, class_name: "BxBlockCategories::MicroCategory", source: :micro_categories, dependent: :destroy
-
-
1
validates :name, uniqueness: true, presence: true
-
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue", dependent: :destroy
-
1
has_many :parent_catalogues, class_name: "BxBlockCatalogue::ParentCatalogue"
-
1
has_one :header_category, class_name: "BxBlockDashboard::HeaderCategory", dependent: :destroy
-
-
1
has_many :custom_fields, as: :fieldable, class_name: "BxBlockCategories::CustomField", dependent: :destroy
-
-
1
accepts_nested_attributes_for :custom_fields, allow_destroy: true
-
-
1
has_one_attached :category_image, dependent: :destroy
-
1
has_one_attached :header_image, dependent: :destroy
-
1
before_validation :strip_name_whitespace
-
-
1
has_one :most_popular_category, class_name: "BxBlockDashboard::MostPopularCategory", dependent: :destroy
-
1
has_many :banners, class_name: "BxBlockDashboard::Banner", dependent: :destroy
-
-
1
private
-
-
1
def strip_name_whitespace
-
1896
self.name = name.strip if name.present?
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class CustomField < ApplicationRecord
-
1
self.table_name = :custom_fields
-
1
belongs_to :fieldable, polymorphic: true
-
-
1
validates :field_name, presence: true, length: { in: 3..30 }, format: { with: /\A[a-zA-Z0-9\s]+\z/, message: "only allows letters, numbers, and spaces" }
-
-
1
has_many :catalogue_contents, class_name: "BxBlockCatalogue::CatalogueContent", dependent: :destroy
-
1
has_many :custom_fields_options, class_name: "BxBlockCategories::CustomFieldsOption", dependent: :destroy
-
1
accepts_nested_attributes_for :custom_fields_options, allow_destroy: true
-
-
1
has_many :catalogues, through: :catalogue_contents, class_name: "BxBlockCatalogue::Catalogue"
-
1
before_save :update_catalogue_contents_custom_field_name
-
1
before_save :strip_whitespace
-
1
validate :check_options_presence
-
-
1
private
-
-
1
def check_options_presence
-
128
if custom_fields_options.blank?
-
errors.add(:base, "At least one custom field option must be present")
-
end
-
end
-
-
1
def update_catalogue_contents_custom_field_name
-
128
catalogue_contents.each do |catalogue_content|
-
2
catalogue_content.update(custom_field_name: field_name)
-
end
-
end
-
-
1
def strip_whitespace
-
128
self.field_name = field_name.strip if field_name.present?
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class CustomFieldsOption < ApplicationRecord
-
1
self.table_name = :custom_fields_options
-
1
belongs_to :custom_field, class_name: "BxBlockCategories::CustomField"
-
1
validates :option_name, presence: true, length: { in: 3..30 }
-
1
before_save :strip_whitespace
-
-
1
private
-
-
1
def strip_whitespace
-
125
self.option_name = option_name.strip if option_name.present?
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class MicroCategory < BxBlockCategories::ApplicationRecord
-
1
self.table_name = :micro_categories
-
-
1
belongs_to :mini_category, class_name: "BxBlockCategories::MiniCategory", foreign_key: :mini_category_id
-
1
has_one :sub_category, through: :mini_category, class_name: "BxBlockCategories::SubCategory", foreign_key: :sub_category_id
-
1
has_one :category, through: :sub_category, class_name: "BxBlockCategories::Category", foreign_key: :parent_id
-
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue"
-
1
has_many :parent_catalogues, class_name: "BxBlockCatalogue::ParentCatalogue"
-
-
1
validates :name, uniqueness: true, presence: true
-
-
1
has_many :custom_fields, as: :fieldable, class_name: "BxBlockCategories::CustomField", dependent: :destroy
-
1
has_many :catalogue_variants, class_name: "BxBlockCatalogue::CatalogueVariant", dependent: :destroy
-
-
1
accepts_nested_attributes_for :custom_fields, allow_destroy: true
-
-
1
before_validation :strip_name_whitespace
-
-
1
private
-
-
1
def strip_name_whitespace
-
148
self.name = name.strip if name.present?
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class MiniCategory < BxBlockCategories::ApplicationRecord
-
1
self.table_name = :mini_categories
-
-
1
belongs_to :sub_category, class_name: "BxBlockCategories::SubCategory", foreign_key: :sub_category_id
-
1
has_one :category, through: :sub_category, class_name: "BxBlockCategories::Category", foreign_key: :parent_id
-
1
has_many :micro_categories, class_name: "BxBlockCategories::MicroCategory", foreign_key: :mini_category_id, dependent: :destroy
-
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue"
-
1
has_many :parent_catalogues, class_name: "BxBlockCatalogue::ParentCatalogue"
-
-
1
has_many :custom_fields, as: :fieldable, class_name: "BxBlockCategories::CustomField", dependent: :destroy
-
1
accepts_nested_attributes_for :custom_fields, allow_destroy: true
-
-
1
validates :name, uniqueness: true, presence: true
-
-
1
before_validation :strip_name_whitespace
-
-
1
private
-
-
1
def strip_name_whitespace
-
167
self.name = name.strip if name.present?
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class SubCategory < BxBlockCategories::ApplicationRecord
-
1
self.table_name = :sub_categories
-
-
1
belongs_to :category, class_name: "BxBlockCategories::Category", foreign_key: :parent_id
-
1
has_many :mini_categories, class_name: "BxBlockCategories::MiniCategory", foreign_key: :sub_category_id, dependent: :destroy
-
1
has_many :micro_categories, through: :mini_categories, class_name: "BxBlockCategories::MicroCategory", dependent: :destroy
-
-
1
validates :name, uniqueness: true, presence: true
-
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue"
-
1
has_many :parent_catalogues, class_name: "BxBlockCatalogue::ParentCatalogue"
-
-
1
has_many :custom_fields, as: :fieldable, class_name: "BxBlockCategories::CustomField", dependent: :destroy
-
1
has_many :banners, class_name: "BxBlockDashboard::Banner", dependent: :destroy
-
1
accepts_nested_attributes_for :custom_fields, allow_destroy: true
-
-
1
before_validation :strip_name_whitespace
-
-
1
private
-
-
1
def strip_name_whitespace
-
233
self.name = name.strip if name.present?
-
end
-
-
end
-
end
-
1
module BxBlockChat
-
1
class AccountsChatsBlock < BxBlockChat::ApplicationRecord
-
1
self.table_name = :accounts_chats
-
1
belongs_to :chat, class_name: "BxBlockChat::Chat"
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
-
1
after_save :update_chat_for_type
-
-
1
validates :chat_id, uniqueness: {scope: :account_id,
-
message: "should added only one time on same chat"}
-
-
1
def update_chat_for_type
-
chat.update(chat_type: "multiple_user") if chat.accounts.count > 2
-
end
-
end
-
end
-
1
module BxBlockChat
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockComments
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockComments
-
1
class Comment < BxBlockComments::ApplicationRecord
-
1
self.table_name = :comments
-
1
if ENV['TEMPLATEAPP_DATABASE']
-
1
include PublicActivity::Model
-
1
tracked owner: proc { |controller, model| controller&.current_user }
-
end
-
-
1
validates :comment, presence: true
-
-
1
belongs_to :account,
-
class_name: "AccountBlock::Account"
-
-
1
belongs_to :commentable, polymorphic: true
-
-
1
def self.policy_class
-
::BxBlockComments::CommentPolicy
-
end
-
end
-
end
-
1
module BxBlockContactUs
-
1
class AdminReply < ApplicationRecord
-
1
self.table_name = :admin_replies
-
1
belongs_to :contact, class_name: 'BxBlockContactUs::Contact'
-
1
has_one_attached :image
-
1
validates :description, presence: true
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockContactUs
-
1
class Contact < BxBlockContactUs::ApplicationRecord
-
1
self.table_name = :contacts
-
1
has_many :admin_replies, class_name: "BxBlockContactUs::AdminReply", dependent: :destroy
-
1
accepts_nested_attributes_for :admin_replies, allow_destroy: true
-
1
validates :title, :email, :contact_type, :description , presence: true
-
1
has_one_attached :image
-
1
enum contact_type: { complaint: "complaint", feedback: "feedback", query: "query"}
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class CouponCode < BxBlockCouponCg::ApplicationRecord
-
1
self.table_name = :coupon_codes
-
-
DISCOUNT_TYPE = {
-
1
percentage: 'percentage'
-
}.freeze
-
-
1
validates :title, length: { maximum: 50 }, presence: true
-
1
validates :code, length: { maximum: 50 }, presence: true
-
1
validates :code, :title, uniqueness: { case_sensitive: false }
-
1
validates :discount, :valid_from, :valid_to, presence: true
-
1
validates :discount, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
-
-
1
validate :end_date_after_start_date
-
1
has_many :subscribe_coupons, class_name: "BxBlockCouponCg::SubscribeCoupon", dependent: :destroy
-
1
has_many :accounts, through: :subscribe_coupons, class_name: "AccountBlock::Account"
-
1
has_many :orders, class_name: "BxBlockShoppingCart::Order"
-
# belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
-
2
scope :active, -> { where("valid_to >= ?", Date.today) }
-
-
1
private
-
-
1
def end_date_after_start_date
-
61
return if valid_to.blank? || valid_from.blank?
-
40
if valid_to < valid_from
-
1
errors.add(:valid_to, "end date must be after the start date")
-
end
-
end
-
-
# MAX_CART_VALUE = 100_000
-
# MAX_DISCOUNT_VALUE = 100_000
-
-
-
# validates :discount_type, acceptance: {
-
# accept: [DISCOUNT_TYPE[:flat], DISCOUNT_TYPE[:percentage]]
-
# }
-
# validate :min_cart_value_not_negative
-
# validate :max_cart_value_less_max_value
-
# validate :discount_value
-
-
# def min_cart_value_not_negative
-
# if min_cart_value.negative?
-
# errors.add(:min_cart_value, "Can't be less than zero")
-
# end
-
# end
-
-
# def max_cart_value_less_max_value
-
# if max_cart_value > MAX_CART_VALUE
-
# errors.add(:max_cart_value, "Can't be more than #{MAX_CART_VALUE}")
-
# end
-
# end
-
-
# def discount_value
-
# if discount.negative? || discount > MAX_DISCOUNT_VALUE
-
# errors.add(:discount, 'Discount value is out of bounds')
-
# end
-
# end
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class SubscribeCoupon < BxBlockCouponCg::ApplicationRecord
-
1
self.table_name = :subscribe_coupons
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :coupon, class_name: "BxBlockCouponCg::CouponCode", foreign_key: :coupon_code_id
-
1
belongs_to :catalouge, class_name: "BxBlockCatalogue::Catalogue",optional: true
-
end
-
end
-
1
module BxBlockCustomAds
-
1
class Advertisement < ApplicationRecord
-
-
1
self.table_name = :advertisements
-
# belongs_to :seller_account, class_name: "BxBlockCustomForm::SellerAccount"
-
-
1
enum status: { inactive: 0, active: 1 }
-
1
enum advertisement_for: { seller: 0, user: 1 }
-
-
1
has_one_attached :banner_ad, dependent: :destroy
-
-
1
validates :name, :description, :start_at, :expire_at, presence: true
-
-
# before_create :add_status
-
-
# after_create :notify_admin
-
-
# def add_status
-
# self.status = 0
-
# end
-
-
# def notify_admin
-
# AdvertisementMailer.notify_admin(advertisement:self).deliver
-
# end
-
-
1
validate :start_at_in_future
-
1
validate :expire_at_after_start_at, on: :create
-
-
1
private
-
-
1
def start_at_in_future
-
15
errors.add(:start_at, "Start date should be in the future") if start_at.present? && start_at < Date.today
-
end
-
-
1
def expire_at_after_start_at
-
15
return unless start_at && expire_at
-
-
15
if expire_at < start_at
-
1
errors.add(:expire_at, "Expiry date should be after the start date")
-
14
elsif expire_at < Date.today
-
errors.add(:expire_at, "Expiry date should be in the future")
-
end
-
end
-
end
-
end
-
1
module BxBlockCustomAds
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockDashboard
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockDashboard
-
1
class AuthorFavoriteBook < ApplicationRecord
-
1
self.table_name = :author_favorite_books
-
-
1
has_many :favorite_book_catalogues, class_name: "BxBlockDashboard::AuthorFavoriteBookCatalogue", dependent: :destroy
-
1
accepts_nested_attributes_for :favorite_book_catalogues, allow_destroy: true
-
1
validates :title, presence: true
-
1
before_save :reset_other_statuses, if: :status_changed_to_true?
-
1
validate :minimum_8_products
-
-
1
private
-
-
1
def minimum_8_products
-
63
selections = favorite_book_catalogues.reject { |s| s.marked_for_destruction? }
-
7
errors.add(:favorite_book_catalogues, "must have at least 8 unique products") if selections.size < 8
-
-
7
product_ids = selections.map(&:catalogue_id)
-
7
errors.add(:favorite_book_catalogues, "cannot have duplicate products") if product_ids.uniq.size != product_ids.size
-
end
-
-
1
def status_changed_to_true?
-
7
status_changed? && status == true
-
end
-
-
1
def reset_other_statuses
-
7
self.class.where.not(id: id).update_all(status: false)
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class AuthorFavoriteBookCatalogue < ApplicationRecord
-
1
self.table_name = :favorite_book_catalogues
-
1
belongs_to :catalogue, class_name: 'BxBlockCatalogue::Catalogue'
-
1
belongs_to :author_favorite_book, class_name: 'BxBlockDashboard::AuthorFavoriteBook'
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class Banner < BxBlockDashboard::ApplicationRecord
-
1
self.table_name = :banners
-
-
1
enum banner_type: {
-
single_image: 0,
-
slideshow: 1,
-
top_banner: 2
-
}
-
-
1
enum section: {
-
header: 0,
-
middle: 1,
-
footer: 2
-
}
-
-
1
belongs_to :banner_group, class_name: 'BxBlockDashboard::BannerGroup', optional: true
-
-
1
has_one_attached :banner_image, dependent: :destroy
-
-
1
validates :title, :button_text, :banner_type, presence: true
-
-
93
validates :description, :section, :banner_image, presence: true, unless: -> {banner_type == BxBlockDashboard::Banner.banner_types.keys.last}
-
-
91
validates :button_link, presence: true, if: -> {banner_type == BxBlockDashboard::Banner.banner_types.keys.last}
-
-
1
belongs_to :category, class_name: "BxBlockCategories::Category", foreign_key: "category_id", optional: true
-
1
belongs_to :sub_category, class_name: "BxBlockCategories::SubCategory", optional: true
-
1
belongs_to :deal, class_name: "BxBlockCatalogue::Deal", optional: true
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue", optional: true
-
-
90
validate :at_least_one_reference_present, unless: -> {banner_type == "top_banner"}
-
90
validate :only_one_reference_attached, unless: -> {banner_type == "top_banner"}
-
-
1
private
-
-
1
def at_least_one_reference_present
-
79
unless category_id.present? || sub_category_id.present? || deal_id.present? || catalogue_id.present?
-
errors.add(:base, "At least one of category, sub category, deal, or catalogue must be present")
-
end
-
end
-
-
1
def only_one_reference_attached
-
79
references = [category_id, sub_category_id, deal_id, catalogue_id]
-
79
if references.count(&:present?) > 1
-
errors.add(:base, "Only one of category, sub category, deal, or catalogue can be attached")
-
end
-
end
-
end
-
end
-
-
1
module BxBlockDashboard
-
1
class BannerGroup < ApplicationRecord
-
1
self.table_name = :banner_groups
-
-
1
validates :group_name, presence: true, uniqueness: true
-
1
has_many :banners, class_name: 'BxBlockDashboard::Banner', dependent: :destroy
-
end
-
end
-
1
module BxBlockDashboard
-
1
class HeaderCategory < ApplicationRecord
-
1
self.table_name = :header_categories
-
1
belongs_to :category, class_name: "BxBlockCategories::Category"
-
1
validates :sequence_no, presence: true, uniqueness: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 6 }
-
end
-
end
-
1
module BxBlockDashboard
-
1
class MostPopularCategory < ApplicationRecord
-
1
self.table_name = :most_popular_categories
-
1
belongs_to :category, class_name: "BxBlockCategories::Category"
-
-
1
validates :sequence_no, presence: true, uniqueness: true, numericality: { only_integer: true,greater_than_or_equal_to: 1, less_than_or_equal_to: 6 }
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TopBrand < ApplicationRecord
-
1
self.table_name = :top_brands
-
-
1
belongs_to :brand, class_name: "BxBlockCatalogue::Brand"
-
-
1
validates :sequence_no, presence: true, uniqueness: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 6 }
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TrendingProduct < ApplicationRecord
-
1
self.table_name = :trending_products
-
1
enum slider: {
-
slider_1: 1,
-
slider_2: 2
-
}
-
1
has_many :trending_product_selections, class_name: "BxBlockDashboard::TrendingProductSelection", dependent: :destroy
-
1
has_many :catalogues, through: :trending_product_selections, class_name: "BxBlockCatalogue::Catalogue"
-
-
1
accepts_nested_attributes_for :trending_product_selections, allow_destroy: true
-
1
has_one_attached :sale_ad_image, dependent: :destroy
-
1
validates :slider, presence: true, uniqueness: true
-
1
validates :sale_ad_image, presence: true
-
1
validate :minimum_6_products
-
-
1
private
-
-
1
def minimum_6_products
-
231
selections = trending_product_selections.reject { |s| s.marked_for_destruction? }
-
33
errors.add(:trending_product_selections, "must have at least 6 unique products") if selections.size < 6
-
-
33
product_ids = selections.map(&:catalogue_id)
-
33
errors.add(:trending_product_selections, "cannot have duplicate products") if product_ids.uniq.size != product_ids.size
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TrendingProductSelection < ApplicationRecord
-
1
self.table_name = :trending_product_selections
-
-
1
belongs_to :trending_product, class_name: "BxBlockDashboard::TrendingProduct"
-
1
belongs_to :catalogue, class_name: 'BxBlockCatalogue::Catalogue'
-
end
-
end
-
1
module BxBlockDashboard
-
1
class WeeklyDeal < ApplicationRecord
-
1
self.table_name = :weekly_deals
-
1
belongs_to :weekly_homiee_deal, class_name: "BxBlockDashboard::WeeklyHomieeDeal"
-
1
belongs_to :deal, class_name: "BxBlockCatalogue::Deal"
-
-
1
has_one_attached :bg_image, dependent: :destroy
-
-
1
validates :caption, :bg_image, presence: true
-
# validates :url, presence: true, format: { with: /\A(?:https:\/\/|www\.)/, message: "should start with 'https://' or 'www.'" }
-
1
validates :discount_percent, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 }
-
-
end
-
end
-
1
module BxBlockDashboard
-
1
class WeeklyHomieeDeal < ApplicationRecord
-
1
self.table_name = :weekly_homiee_deals
-
1
has_many :weekly_deals, class_name: "BxBlockDashboard::WeeklyDeal", dependent: :destroy
-
1
accepts_nested_attributes_for :weekly_deals, allow_destroy: true
-
-
1
validate :start_time_must_be_today_or_later_and_present
-
1
validate :end_date_must_be_today_or_later_and_present
-
-
1
validate :max_weekly_deals
-
-
1
before_save :reset_other_statuses, if: :status_changed_to_true?
-
2
scope :active_homiee_deals, -> { where("end_time >= ? AND status != ?", Date.today, false) }
-
-
1
private
-
-
1
def max_weekly_deals
-
81
selections = weekly_deals.reject { |s| s.marked_for_destruction? }
-
21
if selections.size != 3
-
1
errors.add(:weekly_deals, "must be exactly 3 and cannot be blank")
-
end
-
end
-
-
1
def end_date_must_be_today_or_later_and_present
-
21
if end_time.blank? || (end_time.to_date < Date.current) || (end_time <= Time.current)
-
1
errors.add(:end_date, "must be today or after start time")
-
end
-
end
-
-
1
def start_time_must_be_today_or_later_and_present
-
21
if start_time.blank? || (start_time < Date.current)
-
1
errors.add(:start_time, "must be today or later")
-
end
-
end
-
-
1
def status_changed_to_true?
-
18
status_changed? && status == true
-
end
-
-
1
def reset_other_statuses
-
3
self.class.where.not(id: id).update_all(status: false)
-
end
-
-
end
-
end
-
1
module BxBlockFavourites
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockFavourites
-
1
class Favourite < BxBlockFavourites::ApplicationRecord
-
1
self.table_name = :favourites
-
-
1
belongs_to :favouriteable, polymorphic: true
-
1
belongs_to :user, class_name: "AccountBlock::Account", foreign_key: "user_id"
-
1
belongs_to :product_variant_group, class_name: 'BxBlockCatalogue::ProductVariantGroup', optional: true
-
-
end
-
end
-
1
module BxBlockInvoicebilling
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockInvoicebilling
-
1
class InvoiceBilling < ApplicationRecord
-
1
self.table_name = :invoice_billings
-
-
1
belongs_to :customer, class_name: 'AccountBlock::Account'
-
1
belongs_to :order, class_name: 'BxBlockShoppingCart::Order'
-
1
belongs_to :order_item, class_name: 'BxBlockShoppingCart::OrderItem'
-
-
1
has_one_attached :invoice_pdf, dependent: :destroy
-
-
1
before_create :generate_invoice_number
-
-
1
private
-
-
1
def generate_invoice_number
-
1
self.invoice_number ||= loop do
-
1
random_number = SecureRandom.alphanumeric(7)
-
1
break random_number unless self.class.exists?(invoice_number: random_number)
-
end
-
end
-
-
end
-
end
-
1
module BxBlockLocation
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockLocation
-
1
class Location < ApplicationRecord
-
1
self.table_name = :locations
-
1
reverse_geocoded_by :latitude, :longitude
-
-
1
belongs_to :van, class_name: 'BxBlockLocation::Van'
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class DeliveryRequest < ApplicationRecord
-
1
self.table_name = :delivery_requests
-
-
#enum status: [:pending, :accepted, :rejected]
-
# validates :status, inclusion: { in: statuses.keys, message: "%{value} is not a valid status" }
-
1
validates :order_number, presence: true
-
1
belongs_to :warehouse, class_name: 'BxBlockCatalogue::Warehouse'
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
1
belongs_to :order, class_name: 'BxBlockShoppingCart::Order', optional: true
-
-
1
validate :validate_address
-
1
validate :validate_order_number
-
17
before_save :assign_default_status, if: Proc.new {|a| a.new_record?}
-
-
1
private
-
-
1
def validate_address
-
18
unless self.address_1.present? || self.geo_location.present?
-
1
errors.add(:address_1, "is missing or select geo location")
-
end
-
end
-
-
1
def validate_order_number
-
18
order_statuses = BxBlockOrderManagement::OrderStatus.where(status: ['processing'])
-
18
errors.add(:order_number, "is invalid") unless BxBlockShoppingCart::Order.includes(:order_status).where(order_number: order_number, order_statuses: { id: order_statuses.map(&:id) }).exists?
-
end
-
-
1
def assign_default_status
-
15
self.status = 'pending'
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: order_statuses
-
#
-
# id :bigint not null, primary key
-
# name :string
-
# status :string
-
# active :boolean default(TRUE)
-
# event_name :string
-
# message :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderStatus < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_statuses
-
-
1
has_many :orders, class_name: "BxBlockShoppingCart::Order", dependent: :nullify
-
1
has_many :order_items, class_name: "BxBlockShoppingCart::OrderItem", dependent: :nullify
-
-
1
validates :name, uniqueness: { case_sensitive: false }, format: { with: /\A[a-zA-Z\s]+\z/, message: "only allows letters and spaces" }, presence: true
-
-
-
1
before_save :add_status
-
-
1
scope :new_statuses, lambda {
-
1
where.not(status: %i[
-
in_cart
-
created
-
placed
-
confirmed
-
in_transit
-
delivered
-
cancelled
-
refunded
-
payment_failed
-
returned
-
payment_pending
-
])
-
}
-
-
1
USER_STATUSES = %w[
-
in_cart
-
created
-
placed
-
payment_failed
-
payment_pending
-
].freeze
-
-
1
CUSTOM_STATUSES = %w[
-
in_cart
-
created
-
placed
-
confirmed
-
in_transit
-
delivered
-
cancelled
-
refunded
-
payment_failed
-
returned
-
payment_pending
-
].freeze
-
-
1
private
-
-
1
def add_status
-
225
self.status = name.to_s.downcase.parameterize.underscore unless status.present?
-
# self.event_name = name.to_s.downcase.parameterize.underscore unless event_name.present?
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class StockIntake < ApplicationRecord
-
1
self.table_name = :stock_intakes
-
1
belongs_to :catalogue, class_name: 'BxBlockCatalogue::Catalogue'
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
-
1
validates :stock_value, :stock_qty, presence: true, numericality: { greater_than: 0 }
-
1
validate :ship_date_must_be_today_or_future
-
1
validate :receiving_date_must_be_after_ship_date_and_today
-
-
1
private
-
-
1
def ship_date_must_be_today_or_future
-
11
if ship_date.blank? || ship_date < Date.today
-
2
errors.add(:ship_date, "must be today or a future date")
-
end
-
end
-
-
1
def receiving_date_must_be_after_ship_date_and_today
-
11
if receiving_date.blank? || receiving_date < ship_date || receiving_date < Date.today
-
errors.add(:receiving_date, "must be after ship date and today")
-
end
-
end
-
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class WmsConsignmentOrder < ApplicationRecord
-
1
self.table_name = :wms_consignment_orders
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class WmsEventUpdate < ApplicationRecord
-
1
self.table_name = :wms_event_updates
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class WmsProductInfo < ApplicationRecord
-
1
self.table_name = :wms_product_infos
-
1
belongs_to :seller, class_name: "AccountBlock::Account"
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
end
-
end
-
1
module BxBlockPosts
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockPosts
-
1
class Post < BxBlockPosts::ApplicationRecord
-
1
self.table_name = :posts
-
-
1
include Validators
-
1
IMAGE_CONTENT_TYPES = %w(image/jpg image/jpeg image/png)
-
-
1
has_many_attached :images, dependent: :destroy
-
-
1
belongs_to :category,
-
class_name: 'BxBlockCategories::Category'
-
-
1
belongs_to :sub_category,
-
class_name: 'BxBlockCategories::SubCategory',
-
foreign_key: :sub_category_id, optional: true
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
has_many_attached :media, dependent: :destroy
-
-
1
validates_presence_of :body
-
1
validates :media, blob: {
-
content_type: IMAGE_CONTENT_TYPES,
-
size_range: 1..3.megabytes
-
}
-
-
1
def media_url
-
media_arr = Array.new
-
media.each do |m|
-
media_hash = Hash.new
-
media_hash['url'] = m.service_url(expires_in: Rails.application.config.active_storage.service_urls_expire_in)
-
media_hash['content_type'] = m.content_type
-
media_arr << media_hash
-
end
-
media_arr
-
end
-
-
1
def upload_post_images(images_params)
-
images_to_attach = []
-
-
images_params.each do |image_data|
-
if image_data[:data]
-
decoded_data = Base64.decode64(image_data[:data].split(',')[1])
-
images_to_attach.push(
-
io: StringIO.new(decoded_data),
-
content_type: image_data[:content_type],
-
filename: image_data[:filename]
-
)
-
end
-
end
-
self.images.attach(images_to_attach) if images_to_attach.size.positive?
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
class Preference < BxBlockProfileBio::ApplicationRecord
-
1
self.table_name = :preferences
-
-
1
include Wisper::Publisher
-
# belongs_to :profile_bio
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
-
1
enum smoking: %i[Yes No Sometimes], _prefix: :smoking
-
1
enum drinking: %i[Yes No Occasionally], _prefix: :drinking
-
1
enum religion: %i[Buddhist Christian Hindu Jain Muslim Sikh], _prefix: :religion
-
1
enum height_type: %i[cm inches foot], _prefix: :height_type
-
1
enum body_type: %i[Athletic Average Fat Slim], _prefix: :body_type
-
1
enum seeking: %i[Male Female Both], _prefix: :seeking
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
class ProfileBio < BxBlockProfileBio::ApplicationRecord
-
1
self.table_name = :profile_bios
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
# has_one :preference, dependent: :destroy
-
1
has_many :educations, dependent: :destroy
-
-
1
has_many :achievements, dependent: :destroy
-
# has_and_belongs_to_many :categories,
-
# join_table: :profile_bio_categories,
-
# class_name: 'BxBlockCategories::Category'
-
-
1
has_many :careers, dependent: :destroy
-
# has_many :view_profiles, dependent: :destroy
-
# has_many :likes, as: :likeable, class_name: 'BxBlockLike::Like', dependent: :destroy
-
# has_many :favourites, as: :favouriteable, class_name: 'BxBlockFavourites::Favourite', dependent: :destroy
-
-
1
enum marital_status: %i[Single In-Relationship Engaged Married Divorced Widowed], _prefix: :marital_status
-
1
enum smoking: %i[Yes No Sometimes], _prefix: :smoking
-
1
enum drinking: %i[Yes No Occasionally], _prefix: :drinking
-
# enum looking_for: %i[Friend Marriage Live-In Soul-Mate Business-Colleagues], _prefix: :looking_for
-
1
enum height_type: %i[cm inches foot], _prefix: :height_type
-
1
enum weight_type: %i[kg pounds(lbs)], _prefix: :weight_type
-
-
1
enum body_type: %i[Athletic Average Fat Slim], _prefix: :body_type
-
1
enum mother_tougue: %i[
-
Arabic Bengali Chinese English French German Gujarati Hindi Indonesian Italian
-
Japanese Malayalam Marathi Nepali Portuguese Punjabi Russian Spanish Swahili
-
Tamil Telugu Turkish Urdu
-
], _prefix: :mother_tougue
-
1
enum religion: %i[Buddhist Christian Hindu Jain Muslim Sikh], _prefix: :religion
-
1
enum zodiac: %i[Aquarius Aries Cancer Capricorn Gemini Leo Libra Pisces Sagittarius Scorpio Taurus Virgo],
-
_prefix: :zodiac
-
-
1
validates :languages, presence: true
-
# validates :height, :weight, :height_type, :weight_type, :body_type, :mother_tougue,
-
# :religion, :zodiac, :marital_status, :languages, presence: true
-
-
1
accepts_nested_attributes_for :educations, :achievements, :careers, allow_destroy: true
-
# attr_accessor :distance_away, :is_liked, :is_favourite, :category_ids
-
-
1
INTERESTS_VALUES = [
-
"Sports", "Fitness", "Cooking", "Traveling", "Politics", "Adventures", "Music",
-
"Pets", "Mountains", "Beaches", "Cooking", "Nature", "Photography", "Dancing",
-
"Painting", "Pets", "Music", "Puzzles", "Gardening", "Reading Books", "Handicrafts",
-
"Movies", "Night Outs", "Stargazing", "Internet", "Surfing", "Traveling",
-
"Chit Chat", "Sports", "Adventures", "Trekking", "Hiking", "Yoga", "Workouts",
-
"Baking", "Binge-Watching", "Calligraphy", "Blogging", "Writing", "Drama",
-
"Home Improving", "Journaling", "Knitting", "Martial Arts", "Miniature Art",
-
"Poetry", "Sewing", "Sketching", "Singing", "Video Gaming", "Wood Carving",
-
"Astronomy", "Bird Watching", "Fishing", "Swimming", "Nature"
-
].freeze
-
-
1
PERSONALITY_VALUES = [
-
"Extrovert", "Introvert", "Creative", "Angry", "Cool", "Emotional", "Practical",
-
"Rules Breaker", "Stick To Rules", "Optimistic", "Pessimist", "Hard Work",
-
"Smart Work", "Spendthrift", "Miser", "Good Listener", "Talks a Lot", "Childish",
-
"Matured", "Patient", "Impatient", "Competitive", "Relaxed", "Last-Minute Person",
-
"Pre-Planner", "Foodie", "Book Bug", "Shopaholic", "Morning Person", "Night Owl"
-
].freeze
-
-
1
validates_intersection_of :personality, in: PERSONALITY_VALUES, message: "invalid personality"
-
1
validates_intersection_of :interests, in: INTERESTS_VALUES, message: "invalid interests"
-
-
# after_save :assign_categories
-
# after_create :create_default_preference
-
-
1
def match_profiles(params)
-
return [] if params.nil?
-
-
profiles = profiles_by_discover_for(params[:discover_for])
-
profiles = sender_and_receiver_profiles(profiles)
-
profiles = profiles_based_on_height(profiles)
-
profiles = filter_by_gender(profiles, params[:seeking_for])
-
profiles = filter_new_profiles(profiles, params)
-
profiles = online_profiles(profiles, params)
-
profiles = filter_by_age_range(profiles, preference.age_range_start, preference.age_range_end)
-
profiles = preference_location(profiles)
-
params[:location] = account.location.address
-
filter_by_location(profiles, params)
-
end
-
-
1
def match_params
-
params = {}
-
params[:smoking] = preference.smoking if preference.smoking.present?
-
params[:drinking] = preference.drinking if preference.drinking.present?
-
params[:religion] = preference.religion if preference.religion.present?
-
params[:body_type] = preference.body_type if preference.body_type
-
params
-
end
-
-
1
def profiles_based_on_height(profiles)
-
if [preference.height_type, preference.height_range_start, preference.height_range_end].include?(nil)
-
return profiles
-
end
-
-
params = height_params
-
profiles_ids_1 = begin
-
profiles.where(height: params[:height_start].to_f..params[:height_end].to_f,
-
height_type: params[:height_type]).map(&:id)
-
rescue
-
[]
-
end
-
-
profiles_ids_2 = profiles.where(
-
height: preference.height_range_start.to_f..preference.height_range_end.to_f,
-
height_type: preference.height_type
-
).map(&:id)
-
profiles.where(id: (profiles_ids_1 + profiles_ids_2).uniq)
-
end
-
-
1
def height_params
-
params = {}
-
case preference.height_type
-
when "foot"
-
params = {
-
height_start: (preference.height_range_start.to_f * 30.48).floor,
-
height_end: (preference.height_range_end.to_f * 30.48).floor,
-
height_type: "cm"
-
}
-
when "cm"
-
params = {
-
height_start: convert_cm_to_foot(preference.height_range_start.to_i),
-
height_end: convert_cm_to_foot(preference.height_range_end.to_i),
-
height_type: "foot"
-
}
-
end
-
params
-
end
-
-
1
def profiles_by_discover_for(discover_for)
-
BxBlockProfileBio::ProfileBio.joins(:categories)
-
.where(categories: {name: discover_for})
-
.where(match_params).where.not(account_id: account.id).distinct
-
end
-
-
1
def sender_and_receiver_profiles(profiles)
-
received_ids = profiles.includes(account: :requests).where(accounts: {
-
requests: {account_id: account.id, status: 0}
-
}).map(&:id)
-
sender_ids = profiles.includes(account: :requests).where(accounts: {
-
requests: {sender_id: account.id, status: 0}
-
}).map(&:id)
-
profiles_id = received_ids + sender_ids
-
profiles = profiles.where.not(id: profiles_id.uniq)
-
end
-
-
1
def convert_cm_to_foot(height_value)
-
height_data = (height_value / 2.54).round(8)
-
height_foot = (height_data / 12).floor
-
height_inches = (height_data - (12 * height_foot)).floor
-
"#{height_foot}.#{height_inches}"
-
end
-
-
1
def preference_location(profiles)
-
return profiles if preference.location.blank?
-
results = Geocoder.search(preference.location)
-
near_by = if preference.distance.present?
-
account_locations.near(results.first.coordinates, preference.distance, units: :km)
-
else
-
account_locations.near(results.first.coordinates)
-
end
-
profiles.where(account_id: near_by.map(&:locationable_id))
-
end
-
-
1
def filter_profiles(profiles, params)
-
profiles = filter_by_gender(profiles, params[:seeking_for])
-
profiles = filter_by_location(profiles, params)
-
profiles = filter_by_age_range(profiles, params[:age_range_start], params[:age_range_end])
-
profiles = filter_new_profiles(profiles, params)
-
filter_viewed_profiles(profiles, params)
-
end
-
-
1
def filter_by_gender(profiles, seeking_for)
-
return profiles if seeking_for.blank? || seeking_for == "Both"
-
profiles.joins(:account).where(accounts: {gender: seeking_for})
-
end
-
-
1
def filter_by_age_range(profiles, age_range_start, age_range_end)
-
return profiles if age_range_start.blank? || age_range_end.blank?
-
-
profiles.joins(:account).where(accounts: {
-
age: age_range_start.to_i..age_range_end.to_i
-
}).distinct
-
end
-
-
1
def filter_new_profiles(profiles, params)
-
return profiles unless ActiveModel::Type::Boolean.new.cast(params[:new_profiles])
-
# get the 24 hours profiles
-
profiles.where(created_at: Time.now.all_day).order("profiles.created_at desc")
-
end
-
-
1
def online_profiles(profiles, params)
-
return profiles unless ActiveModel::Type::Boolean.new.cast(params[:online_profiles])
-
-
ids = $redis_onlines.keys
-
profiles = profiles.where(account_id: ids)
-
end
-
-
1
def filter_viewed_profiles(profiles, params)
-
return profiles unless ActiveModel::Type::Boolean.new.cast(params[:viewed_profiles])
-
profiles.includes(:view_profiles).where(view_profiles: {view_by_id: id})
-
end
-
-
1
def filter_by_location(profiles, params)
-
return profiles if ActiveModel::Type::Boolean.new.cast(params[:recommended]) == false || params[:location].blank?
-
-
near_by = locations_by_geocoder(params)
-
profiles.where(account_id: near_by.map(&:locationable_id))
-
end
-
-
1
def locations_by_geocoder(params)
-
results = Geocoder.search(params[:location])
-
params[:distance].blank? ?
-
account_locations.near(results.first.coordinates) :
-
account_locations.near(results.first.coordinates, params[:distance], units: :km)
-
end
-
-
1
def account_locations
-
@locations ||= BxBlockLocation::Location.where(locationable_type: "AccountBlock::Account")
-
end
-
-
1
def liked_profile(profiles)
-
profiles.each do |profile|
-
profile.is_liked = BxBlockLike::Like.find_by(
-
like_by_id: account_id,
-
likeable_id: profile.account.id,
-
likeable_type: "AccountBlock::Account"
-
).present?
-
end
-
end
-
-
1
def favourite_profile(profiles)
-
profiles.each do |profile|
-
profile.is_favourite = BxBlockFavourites::Favourite.where(
-
favourite_by_id: account_id, profile_bio_id: profile.id
-
).last&.status == "Favourite"
-
end
-
end
-
-
1
private
-
-
1
def assign_categories
-
return unless category_ids.present?
-
-
categories.delete_all
-
category_ids.each { |c| categories << BxBlockCategories::Category.find(c) }
-
create_default_preference
-
end
-
-
1
def create_default_preference
-
arr_hash1 = {}
-
category_names.each { |name| arr_hash1[name.to_sym.downcase] = false }
-
categories.reload.map(&:name).each { |c| arr_hash1[c.to_sym] = true }
-
preference.present? ? preference.update(arr_hash1) : create_preference(arr_hash1)
-
end
-
-
1
def category_names
-
BxBlockCategories::Category.all.pluck(:name)
-
end
-
-
1
def self.distance_calculate(accounts, user)
-
accounts.each do |acc|
-
next if user&.location.blank? || acc&.location.blank?
-
user_location = [user.location.latitude, user.location.longitude]
-
acc_location = [acc.location["latitude"], acc.location["longitude"]]
-
acc.distance_away = Geocoder::Calculations.distance_between(
-
user_location, acc_location, units: :km
-
).round(2)
-
end
-
end
-
end
-
end
-
1
module BxBlockPushNotifications
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockPushNotifications
-
1
class PushNotification < ApplicationRecord
-
1
require 'fcm'
-
1
self.table_name = :push_notifications
-
-
1
belongs_to :push_notificable, polymorphic: true
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
validates :remarks, presence:true
-
1
before_create :send_push_notification
-
-
1
def send_push_notification
-
if push_notificable.activated && push_notificable.device_id &&
-
push_notificable.privacy_setting["#{notify_type}".to_sym]
-
fcm_client = FCM.new(ENV['FCM_SEVER_KEY']) # set your FCM_SERVER_KEY
-
options = { priority: 'high',
-
data: {
-
message: remarks,
-
notify_type: "#{notify_type}",
-
account_id: account_id
-
},
-
notification: {
-
body: remarks,
-
sound: 'default'
-
}
-
}
-
registration_id = push_notificable.device_id
-
# A registration ID looks something like:
-
#“dAlDYuaPXes:APA91bFEipxfcckxglzRo8N1SmQHqC6g8SWFATWBN9orkwgvTM57kmlFOUYZAmZKb4XGGOOL
-
#9wqeYsZHvG7GEgAopVfVupk_gQ2X5Q4Dmf0Cn77nAT6AEJ5jiAQJgJ_LTpC1s64wYBvC”
-
fcm_client.send(registration_id, options)
-
end
-
rescue Exception => e
-
e
-
end
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class ProductView < ApplicationRecord
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :user, class_name: 'AccountBlock::Account', optional: true
-
-
1
before_save :assign_viewed_at, if: :new_record?
-
-
1
private
-
-
1
def assign_viewed_at
-
4
self.viewed_at = Time.current
-
end
-
end
-
end
-
1
module BxBlockSeoSetting
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockSeoSetting
-
1
class SeoSetting < BxBlockSeoSetting::ApplicationRecord
-
1
self.table_name = :seo_settings
-
1
validates :page_name, presence: true, uniqueness: true
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class Order < ApplicationRecord
-
1
include Wisper::Publisher
-
1
self.table_name = :shopping_cart_orders
-
-
# BUFFER_TIME = 20 #in minute
-
1
ORDER_NUMBER_FORMAT = "0000-0000000000"
-
-
#order status are
-
#upcomming = 'scheduled', ongoing = 'on_going', history = 'cancelled or completed
-
# enum status: { scheduled: 0, on_going: 1, cancelled: 2, completed: 3 }
-
-
1
has_many :order_items, class_name: 'BxBlockShoppingCart::OrderItem', dependent: :destroy
-
1
belongs_to :shipping_address, class_name: "AccountBlock::UserDeliveryAddress", optional: true, foreign_key: :address_id
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue", through: :order_items
-
1
has_many :sellers, class_name: "AccountBlock::Account", through: :catalogues, source: :seller
-
# belongs_to :address, class_name: 'BxBlockAddress::Address', optional: true
-
1
belongs_to :customer, class_name: 'AccountBlock::Account', foreign_key: :customer_id
-
-
1
belongs_to :coupon_code, class_name: "BxBlockCouponCg::CouponCode", optional: true
-
-
1
belongs_to :order_status, class_name: 'BxBlockOrderManagement::OrderStatus', foreign_key: :order_status_id, optional: true
-
1
has_many :delivery_requests, class_name: 'BxBlockOrderManagement::DeliveryRequest', dependent: :nullify
-
1
has_many :shipped_order_details, class_name: 'BxBlockShoppingCart::ShippedOrderDetail', dependent: :destroy
-
1
has_many :return_exchange_requests, class_name: 'BxBlockShoppingCart::ReturnExchangeRequest', dependent: :destroy
-
1
has_many :invoice_billings, class_name: 'BxBlockInvoicebilling::InvoiceBilling', dependent: :destroy
-
-
925
validate :check_order_status, if: Proc.new {|a| !a.new_record?}
-
714
validate :check_warehouse_catalogue_stocks, on: :update, if: -> { order_status&.status == 'ordered' }
-
-
1
before_create :assign_default_order_status
-
# after_create :set_current_order
-
# after_update :update_current_order
-
1
after_commit :set_or_update_current_order
-
-
1
before_create :add_order_number
-
-
1
scope :completed, -> { joins(:order_status).where('order_statuses.status': 'completed') }
-
2
scope :completed_cancelled, -> { joins(:order_status).where(order_statuses: { status: ['delivered','completed', 'cancelled'] }) }
-
-
-
496
before_update :update_order_placed_at, if: -> { order_status&.status == 'ordered' }
-
496
before_update :update_delivered_at, if: -> { order_status&.status.in?(['delivered', 'completed']) }
-
-
1
after_create :assign_default_shipping_address
-
496
after_update :increment_purchase_count_on_product, if: -> { order_status&.status.in?(['ordered']) }
-
496
after_update :update_stocks, if: -> { order_status&.status.in?(['ordered']) }
-
1
after_update :notify_seller_if_ordered, :notify_seller_if_delivered
-
496
after_update :update_shipping_address, if: -> { order_status&.status.in?(['ordered']) && shipping_first_name.nil? }
-
-
# scope :completed_order, -> { where(order_status.status: 'completed') }
-
-
1
private
-
-
1
def notify_seller_if_ordered
-
495
send_email_notification_if_status_changed('ordered', 'Your Product Is Selling', 'product_sale_notification')
-
495
notify_seller_if_payment_done
-
495
send_email_notification_if_status_changed('ordered', 'Order Confirmation', 'order_placement_notification', self.customer)
-
end
-
-
1
def notify_seller_if_payment_done
-
495
send_email_notification_if_status_changed('ordered', 'Payment Processed', 'payment_notification')
-
end
-
-
1
def notify_seller_if_delivered
-
495
send_email_notification_if_status_changed('delivered', 'Your product is delivered', 'product_delivery_notification')
-
495
send_email_notification_if_status_changed('delivered',"Order Delivered (#{self.order_number})",'order_delivered_successfully_notification', self.customer)
-
495
send_email_notification_if_status_changed('delivered',"Rate your delivered products – #{self.order_number}",'rate_your_delivered_product_notification', self.customer)
-
end
-
-
# def notify_buyer_if_shipped
-
# send_email_notification_if_status_changed('shipped', 'Your order is shipped', 'shipment_confirmation_notification', self.customer)
-
# send_email_notification_if_status_changed('shipped', 'Out for Delivery', 'out_for_delivery_notification', self.customer)
-
# end
-
-
1
def send_email_notification_if_status_changed(expected_status, subject, template, buyer = nil)
-
2970
if saved_change_to_order_status_id? && order_status&.status == expected_status
-
81
order_items.includes(:catalogue).each do |order_item|
-
39
account = buyer ? buyer : order_item.catalogue.seller
-
39
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: account, subject: subject, file: template, order_item: order_item, order: self)
-
.notification.deliver_now
-
end
-
end
-
end
-
-
1
def assign_default_order_status
-
210
self.order_status = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Scheduled')
-
210
self.status = 'scheduled'
-
end
-
-
1
def check_order_status
-
713
status_ids = BxBlockOrderManagement::OrderStatus.where(status: ['completed', 'ordered']).map(&:id)
-
# return if shipping_first_name_changed?
-
713
if order_status_id_was.in?(status_ids) && order_status&.status.in?(['scheduled', 'on_going', 'ordered'])
-
2
errors.add(:invalid_request, 'Cannot update the order status back to scheduled, on_going, or ordered once it is completed or ordered')
-
end
-
end
-
-
1
def check_warehouse_catalogue_stocks
-
19
out_of_stock_items = order_items.select do |order_item|
-
12
if order_item.catalogue
-
16
order_item.catalogue.warehouse_catalogues.any? { |wc| wc.stocks < order_item.quantity }
-
end
-
end
-
-
19
if out_of_stock_items.any?
-
2
out_of_stock_details = out_of_stock_items.map { |item| { id: item.catalogue_id, product_title: item.catalogue.product_title } }
-
1
errors.add(:order_items, out_of_stock: out_of_stock_details)
-
end
-
end
-
-
1
def set_or_update_current_order
-
494
return unless customer.present?
-
-
494
if order_status && order_status.status.in?(%w[on_going scheduled])
-
419
customer.current_order = self.id
-
else
-
75
customer.current_order = nil
-
end
-
-
494
if customer.save
-
return
-
else
-
errors.add(:customer, "Failed to update current order for customer: #{customer.errors.full_messages}")
-
raise ActiveRecord::Rollback
-
end
-
end
-
-
1
def add_order_number
-
210
self.order_number = Order.next_order_number
-
end
-
-
1
def self.next_order_number
-
211
return ORDER_NUMBER_FORMAT.succ if Order.count.zero?
-
-
211
last_order_number = Order.last.order_number
-
211
numeric_part = last_order_number.split('-')[1].to_i
-
211
next_numeric_part = numeric_part.succ
-
-
211
next_order_number = "#{next_numeric_part.to_s.rjust(10, '0')}"
-
211
"#{ORDER_NUMBER_FORMAT.split('-')[0]}-#{next_order_number}"
-
end
-
-
1
def update_order_placed_at
-
16
self.order_placed_at = Time.current unless order_placed_at.present?
-
end
-
-
1
def update_delivered_at
-
26
self.delivered_at = Time.current unless delivered_at.present?
-
end
-
-
1
def assign_default_shipping_address
-
210
shipping_address_id = nil
-
-
210
if customer&.user_delivery_addresses&.any?
-
4
user_address = customer.user_delivery_addresses.find_by(is_default: true)
-
-
4
shipping_address_id = user_address&.id
-
end
-
210
update(address_id: shipping_address_id)
-
end
-
-
#to store static shipped address after ordered
-
1
def update_shipping_address
-
16
if shipping_address
-
2
update_columns(
-
shipping_first_name: shipping_address.first_name,
-
shipping_last_name: shipping_address.last_name,
-
shipping_address_1: shipping_address.address_1,
-
shipping_address_2: shipping_address.address_2,
-
shipping_city: shipping_address.city,
-
shipping_state: shipping_address.state,
-
shipping_phone_number: shipping_address.phone_number,
-
shipping_zip_code: shipping_address.zip_code
-
)
-
end
-
end
-
-
1
def increment_purchase_count_on_product
-
16
return unless catalogues.present?
-
-
8
catalogues.each do |catalogue|
-
8
catalogue.increment!(:purchased_count)
-
end
-
end
-
-
1
def update_stocks
-
16
order_items.each do |order_item|
-
9
catalogue = order_item.catalogue
-
9
next unless catalogue.present?
-
-
9
if catalogue.warehouse_catalogues.present?
-
3
catalogue.warehouse_catalogues.each do |warehouse_catalogue|
-
3
new_stock = warehouse_catalogue.stocks - order_item.quantity
-
3
if new_stock <= 0
-
1
warehouse_catalogue.update!(stocks: 0)
-
else
-
2
warehouse_catalogue.decrement!(:stocks, order_item.quantity)
-
end
-
end
-
end
-
-
9
catalogue.update_total_stocks
-
end
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class OrderItem < ApplicationRecord
-
1
self.table_name = :shopping_cart_order_items
-
1
belongs_to :order, class_name: 'BxBlockShoppingCart::Order', foreign_key: :order_id
-
1
belongs_to :order_status, class_name: 'BxBlockOrderManagement::OrderStatus', foreign_key: :order_status_id, optional: true
-
1
belongs_to :catalogue, class_name: 'BxBlockCatalogue::Catalogue', foreign_key: :catalogue_id
-
1
has_one :seller, through: :catalogue
-
1
belongs_to :product_variant_group, class_name: 'BxBlockCatalogue::ProductVariantGroup', optional: true
-
1
has_many :return_reason_details, class_name: 'BxBlockShoppingCart::ReturnReasonDetail', foreign_key: :shopping_cart_order_item_id, dependent: :destroy
-
1
has_and_belongs_to_many :return_exchange_requests, class_name: 'BxBlockShoppingCart::ReturnExchangeRequest', join_table: :order_items_return_exchange_requests
-
1
has_many :invoice_billings, class_name: 'BxBlockInvoicebilling::InvoiceBilling', dependent: :destroy
-
1
has_many :review_and_ratings, class_name: "BxBlockCatalogue::Review", foreign_key: :order_item_id, dependent: :destroy
-
1
has_one :shipped_order_detail, class_name: 'BxBlockShoppingCart::ShippedOrderDetail', dependent: :destroy
-
1
validate :check_stock_availability, on: :create
-
1
scope :available_status, -> {
-
joins(:order_status).where(order_statuses: { name: ['Processing', 'Shipped', 'Delivered'] })
-
}
-
-
1
before_save :assign_price_to_order_item
-
1
after_save :update_order_total
-
1
after_destroy :update_order_total
-
-
1
validate :order_can_be_updated
-
1
after_update :notify_sellers_if_returned, :notify_sellers_if_return_completed, :notify_buyer_if_pickup
-
-
1
after_update :notify_buyer_if_shipped, :update_stock_if_catalogue_return
-
-
-
1
def notify_sellers_if_returned
-
32
send_email_notification_if_status_changed('return', 'Refund/Return Notification', 'return_refund_notification')
-
32
send_email_notification_if_status_changed('return', 'Return Request Accepted', 'return_request_accepted_notification', order.customer)
-
end
-
-
1
def notify_buyer_if_pickup
-
32
send_email_notification_if_status_changed('pickup_initiated', 'Return Picked Up', 'return_pickup_information_notification', order.customer)
-
end
-
-
1
def notify_buyer_if_shipped
-
32
if self.order_status&.status == 'shipped'
-
1
send_email_notification_if_status_changed('shipped', 'Your order is shipped', 'shipment_confirmation_notification', self.order.customer)
-
1
send_email_notification_if_status_changed('shipped', 'Out for Delivery', 'out_for_delivery_notification', self.order.customer)
-
end
-
end
-
-
1
def notify_sellers_if_return_completed
-
32
send_email_notification_if_status_changed('refunded', "Return Completed: Order ID - #{order.order_number}", 'return_complete_notification')
-
32
send_email_notification_if_status_changed('refund_initiated', "Return Completed", 'return_completed_buyer_notification', order.customer)
-
32
send_email_notification_if_status_changed('refund_initiated', "Refund Initiated - (#{catalogue&.product_title})", 'refund_initiated_notification', order.customer)
-
end
-
-
1
def send_email_notification_if_status_changed(expected_status, subject, template, buyer = nil)
-
194
if saved_change_to_order_status_id? && order_status&.status == expected_status
-
10
account = buyer ? buyer : catalogue.seller
-
10
BxBlockEmailNotifications::SendEmailNotificationService
-
.with(account: account, subject: subject, file: template, order_item: self, order: order)
-
.notification.deliver_later
-
end
-
end
-
-
1
def order_can_be_updated
-
201
if ['cancelled', 'completed'].include?(order&.order_status&.name)
-
errors.add(:order, "has already been #{order.order_status&.name}")
-
end
-
end
-
-
1
def assign_price_to_order_item
-
203
discount_price = assign_discount_to_order
-
-
203
if discount_price > 0
-
3
self.price = discount_price
-
else
-
200
self.price = catalogue.product_content&.retail_price&.to_f&.round(2) || 0.0
-
end
-
end
-
-
1
def active_offer
-
609
if catalogue.catalogue_offer&.active?
-
14
catalogue.catalogue_offer
-
else
-
nil
-
end
-
end
-
-
1
def active_approved_deal
-
616
seller_deal = catalogue.deal_catalogues.where(status: 'approved').last
-
616
seller_deal if seller_deal&.deal&.active?
-
end
-
-
1
def assign_discount_to_order
-
602
retail_price = catalogue.product_content&.retail_price.to_f
-
-
602
if active_offer.present?
-
7
sale_price = active_offer.sale_price.to_f.round(2)
-
7
self.discount_price = (sale_price > retail_price) ? 0 : -(retail_price - sale_price)
-
7
return sale_price
-
end
-
-
595
if active_approved_deal.present?
-
7
if active_approved_deal.deal.discount_type == 'flat'
-
deal_price = active_approved_deal.deal_price.to_f.round(2)
-
self.discount_price = (deal_price > retail_price) ? 0 : -(retail_price - deal_price)
-
return deal_price
-
-
7
elsif active_approved_deal.deal.discount_type == 'percentage'
-
7
discount = (retail_price * active_approved_deal.deal.discount_value / 100.0).round(2)
-
7
self.discount_price = -(discount)
-
7
return (retail_price - discount).round(2)
-
else
-
0.0
-
end
-
end
-
-
588
self.discount_price = 0.0
-
588
return 0.0
-
end
-
-
1
def update_order_total
-
217
if order && order.valid?
-
215
order.update(
-
total_fees: calculate_total_price,
-
total_items: count_total_items,
-
discount: calculate_total_discount,
-
total_tax: calculate_total_tax,
-
final_price: calculate_final_price.round(2)
-
)
-
else
-
2
errors.add(:base, 'Order is not valid')
-
end
-
end
-
-
1
def calculate_total_fees
-
order.order_items.map {|item| item.price*item.quantity }.sum.round(2)
-
end
-
-
1
def calculate_total_price
-
828
order.order_items.map { |item| (item&.catalogue&.product_content&.retail_price&.to_f || 0) * item.quantity }.sum.round(2)
-
end
-
-
1
def count_total_items
-
414
order.order_items.map {|item| item.quantity }.sum
-
end
-
-
1
def calculate_total_discount
-
430
order.order_items.map do |item|
-
398
retail_price = item.catalogue.product_content&.retail_price.to_f
-
398
discount_price = item.assign_discount_to_order
-
398
if discount_price.zero? || discount_price >= retail_price
-
394
0.0
-
else
-
4
discount_amount = (retail_price - discount_price) * item.quantity
-
4
discount_amount.round(2)
-
end
-
end.sum
-
end
-
-
1
def calculate_final_price
-
216
total_price = calculate_total_price
-
216
total_discount = calculate_total_discount
-
216
total_tax = calculate_total_tax
-
-
216
(total_price - total_discount + total_tax).round(2)
-
end
-
-
1
def calculate_final_discount_price
-
1
final_discount = 0
-
1
order.order_items.each do |item|
-
2
if item.discount_price > 0
-
1
final_discount += (item.discount_price*item.quantity)
-
else
-
1
final_discount += (item.price*item.quantity)
-
end
-
end
-
1
final_discount
-
end
-
-
1
def calculate_total_tax
-
828
order.order_items.map {|item| item.quantity*item.taxable_value }.reject(&:blank?).sum.round(2)
-
end
-
-
1
def self.get_favourites(object)
-
22
favourites = nil
-
-
22
favourites = object.product_variant_group&.favourites if object.product_variant_group
-
22
favourites ||= object.catalogue&.favourites if object.catalogue.present?
-
-
22
favourites&.select { |fav| fav.user_id == object.order.customer_id }&.last
-
end
-
-
1
def check_stock_availability
-
168
available_stock = catalogue&.stocks || 0
-
-
168
if quantity > available_stock
-
1
errors.add(:quantity, "This seller has only #{available_stock} of these available.")
-
end
-
end
-
-
1
def update_stock_if_catalogue_return
-
32
if catalogue&.present? && order_status&.status == 'qc_passed' || order_status&.status == 'rejected'
-
3
catalogue.increment!(:stocks, quantity.to_i)
-
3
catalogue.warehouse_catalogues&.first&.increment!(:stocks, quantity.to_i)
-
end
-
end
-
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ReturnExchangeRequest < ApplicationRecord
-
1
self.table_name = :return_exchange_requests
-
-
1
belongs_to :customer, class_name: 'AccountBlock::Account'
-
1
belongs_to :order, class_name: 'BxBlockShoppingCart::Order'
-
1
has_and_belongs_to_many :order_items, class_name: 'BxBlockShoppingCart::OrderItem', join_table: :order_items_return_exchange_requests
-
-
1
validates :order_number, :request_type, :request_reason, presence: true
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ReturnReasonDetail < ApplicationRecord
-
1
self.table_name = :return_reason_details
-
-
1
enum reason_type: %i[return_reason pickup_and_delivery reason_for_qc_fail]
-
1
belongs_to :order_item, class_name: 'BxBlockShoppingCart::OrderItem', foreign_key: :shopping_cart_order_item_id
-
1
validates :title, :details, :reason_type, presence: true
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class ShippedOrderDetail < ApplicationRecord
-
1
self.table_name = :shipped_order_details
-
-
1
belongs_to :order, class_name: 'BxBlockShoppingCart::Order', foreign_key: :order_id, optional: true
-
1
belongs_to :order_item, class_name: 'BxBlockShoppingCart::OrderItem', foreign_key: :order_item_id, optional: true
-
1
validates :courier_name, :tracking_number, presence: true
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class Store < ApplicationRecord
-
1
self.table_name = :stores
-
1
validates :store_year,:store_url,:website_social_url, presence: true
-
1
validates :store_name, presence: true , uniqueness: true
-
1
has_one_attached :brand_trade_certificate, dependent: :destroy
-
1
has_many :store_menus, class_name: "BxBlockStoreManagement::StoreMenu", dependent: :destroy
-
1
has_many :store_dashboard_sections, class_name: "BxBlockStoreManagement::StoreDashboardSection", dependent: :destroy
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
belongs_to :brand, class_name: "BxBlockCatalogue::Brand", optional: false
-
1
validates :brand_trade_certificate ,presence: true
-
1
validate :one_brand_per_store
-
-
1
private
-
-
1
def one_brand_per_store
-
37
if brand && BxBlockStoreManagement::Store.where(brand_id: brand_id).where.not(id: id).exists?
-
errors.add(:brand, "can only be associated with one store")
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreDashboardSection < ApplicationRecord
-
1
self.table_name = :store_dashboard_sections
-
1
validates :section_name, presence: true, inclusion: { in: %w(section_1 section_2 section_3 banner) }
-
19
validates :section_type, presence: true, inclusion: { in: %w(1_grid_layout 2_grids_layout 3_grids_layout 4_grids_layout) }, unless: -> { section_name == 'banner' }
-
1
has_one_attached :banner_image, dependent: :destroy
-
10
validates :banner_name, presence: true, if: -> { section_name == 'banner' }
-
10
validates :banner_url, allow_blank: true, format: { with: /\A(?:https:\/\/|www\.)[^\s]+\z/, message: "should start with 'https://' or 'www.'" }, if: -> { section_name == 'banner' }
-
1
belongs_to :store, class_name: "BxBlockStoreManagement::Store", foreign_key: :store_id
-
1
has_many :store_section_grids, class_name: "BxBlockStoreManagement::StoreSectionGrid", dependent: :destroy
-
1
accepts_nested_attributes_for :store_section_grids, allow_destroy: true
-
-
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreMenu < ApplicationRecord
-
1
self.table_name = :store_menus
-
-
1
belongs_to :store, class_name: "BxBlockStoreManagement::Store", foreign_key: :store_id
-
1
has_one_attached :cover_image, dependent: :destroy
-
1
has_one_attached :logo, dependent: :destroy
-
-
1
validate :header_validation
-
1
validates :position, presence: true, uniqueness: { scope: :store_id }
-
11
validates :title, presence: true, unless: -> { store_name.present? }
-
1
has_and_belongs_to_many :catalogues, join_table: 'catalogues_store_menus', class_name: "BxBlockCatalogue::Catalogue", optional: true
-
-
1
private
-
-
1
def header_validation
-
10
if store_name.present?
-
2
if !cover_image.attached?
-
1
errors.add(:cover_image, "must be attached when store name is present")
-
end
-
2
if !logo.attached?
-
1
errors.add(:logo, "must be attached when store name is present")
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreSectionGrid < ApplicationRecord
-
1
self.table_name = :store_section_grids
-
1
belongs_to :store_dashboard_section, class_name: "BxBlockStoreManagement::StoreDashboardSection"
-
1
has_one :store, through: :store_dashboard_section, class_name: "BxBlockStoreManagement::Store"
-
1
validates :grid_name, presence: true
-
1
validates :grid_no, presence: true, inclusion: { in: %w(grid_1 grid_2 grid_3 grid_4) }, uniqueness: { scope: :store_dashboard_section_id }
-
1
validates :grid_url, allow_blank: true, format: { with: /\A(?:https:\/\/|www\.)[^\s]+\z/, message: "should start with 'https://' or 'www.'" }
-
1
has_one_attached :grid_image, dependent: :destroy
-
-
end
-
end
-
1
module BxBlockSupport
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockSupport
-
1
class SocialPlatform < ApplicationRecord
-
1
self.table_name = :social_platforms
-
1
validates :social_media ,:social_media_url, presence: true, uniqueness: true
-
-
1
has_one_attached :social_icon, dependent: :destroy
-
-
1
validate :validate_social_icon_type
-
-
1
def validate_social_icon_type
-
4
allowed_types = %w(image/jpeg image/jpg image/png image/webp)
-
-
4
if social_icon.attached? && !social_icon.content_type.in?(allowed_types)
-
errors.add(:social_icon, 'must be a JPEG/JPG/PNG/WebP file')
-
end
-
end
-
end
-
end
-
1
module BxBlockSupport
-
1
class StaticPage < ApplicationRecord
-
1
self.table_name = :static_pages
-
1
validates :title, presence:true, uniqueness: true
-
1
validates :content, presence: true
-
end
-
end
-
1
module BxBlockSupport
-
1
class Support < ApplicationRecord
-
1
self.table_name = :supports
-
1
validates :first_name, :last_name, :email, :details, presence: true
-
end
-
end
-
1
module BxBlockSupport
-
1
class SupportDocument < ApplicationRecord
-
1
self.table_name = :support_documents
-
-
1
validates :content, presence: true
-
1
validates :page_title, presence: true, uniqueness: true
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class PrivacyAndLegalPolicy < ApplicationRecord
-
-
1
self.table_name = :bx_block_termsandconditions_privacy_nad_legal_policies
-
-
1
validates :title, presence: true, uniqueness: true
-
1
validates :content, presence: true
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class SellerStaticPage < ApplicationRecord
-
1
self.table_name = :seller_static_pages
-
-
1
validates :content, presence: true
-
1
validates :title, presence: true, uniqueness: true
-
-
4
scope :header_pages, -> { where(section: 'header') }
-
5
scope :footer_pages, -> { where(section: 'footer') }
-
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class TermsPolicy < ApplicationRecord
-
-
1
self.table_name = :terms_policies
-
-
1
validates :content, presence: true
-
1
validates :page_title, presence: true, uniqueness: true
-
-
end
-
end
-
1
module AccountBlock
-
1
class AccountSerializer < BuilderBase::BaseSerializer
-
1
attributes(
-
:first_name,
-
:last_name,
-
:company_or_store_name,
-
:email,
-
:full_name,
-
:full_phone_number,
-
:phone_number,
-
:country_code,
-
:user_type,
-
:language,
-
:activated,
-
:created_at,
-
:updated_at,
-
:device_id,
-
:unique_auth_id,
-
:current_order)
-
-
1
attribute :country_code do |object|
-
330
country_code_for object
-
end
-
-
1
attribute :phone_number do |object|
-
330
phone_number_for object
-
end
-
-
1
attribute :profile_picture do |object|
-
330
if object.profile_picture.attached?
-
1
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.profile_picture, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.profile_picture, only_path: true)
-
end
-
end
-
-
1
attribute :seller_rating do |object|
-
330
reviews = object.review_and_ratings.approved_reviews.where(review_type: 'seller')
-
330
total_count = reviews.count
-
330
if reviews.present?
-
{
-
72
average_rating: average_rating(reviews).round(1),
-
total_reviews: total_count
-
}
-
end
-
end
-
-
1
attribute :document_status do |object|
-
330
get_document_status(object)
-
end
-
-
1
attribute :first_time_login do |object|
-
330
set_first_time_login(object)
-
end
-
-
1
class << self
-
1
private
-
-
1
def country_code_for(object)
-
330
return nil unless Phonelib.valid?(object.full_phone_number)
-
330
Phonelib.parse(object.full_phone_number).country_code
-
end
-
-
1
def phone_number_for(object)
-
330
return nil unless Phonelib.valid?(object.full_phone_number)
-
330
Phonelib.parse(object.full_phone_number).raw_national
-
end
-
-
1
def average_rating(reviews)
-
72
total_reviews = reviews.count
-
72
return 0 if total_reviews.zero?
-
-
72
total_rating = reviews.sum(&:rating)
-
72
total_rating.to_f / total_reviews
-
end
-
-
1
def get_document_status(account)
-
330
@seller_documents = account.seller_documents
-
330
if @seller_documents.blank?
-
327
"No documents uploaded"
-
3
elsif @seller_documents.all?(&:approved?)
-
1
"Your document has been verified"
-
2
elsif @seller_documents.any?(&:rejected?)
-
1
rejected_documents = @seller_documents.select(&:rejected?).map(&:document_name)
-
1
"Rejected: #{rejected_documents.join(', ')}"
-
else
-
1
"Your Document verification is in progress"
-
end
-
end
-
-
1
def set_first_time_login(account)
-
330
if account.last_visit_at.nil? && @seller_documents.present? && @seller_documents.all?(&:approved?)
-
1
account.update(last_visit_at: Time.now)
-
1
return true
-
else
-
329
return false
-
end
-
end
-
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SellerDocumentSerializer < BuilderBase::BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
1
attributes *[
-
:document_type,
-
:document_name,
-
:vat_reason,
-
:account_no,
-
:iban,
-
:bank_address,
-
:name,
-
:bank_name,
-
:swift_code,
-
:approved,
-
:rejected,
-
:reason_for_rejection,
-
:created_at,
-
:account_id
-
]
-
-
1
attributes :document_files do |object|
-
3
if object.document_files.attached?
-
6
object.document_files.map { |file| ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(file.blob, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(file.blob, only_path: true) }.compact
-
end
-
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SmsOtpSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:full_phone_number,
-
:pin,
-
:activated,
-
:valid_until,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
1
module AccountBlock
-
1
class SuggestionFeedbackSerializer < BuilderBase::BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
1
attributes *[
-
:detail_type,
-
:detail,
-
:first_name,
-
:last_name,
-
:email,
-
:created_at
-
]
-
-
1
attributes :account do |object|
-
3
object.account&.serializable_hash
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class UserDeliveryAddressSerializer < BuilderBase::BaseSerializer
-
-
1
attributes *[
-
:first_name, :last_name, :address_1, :address_2, :phone_number, :state, :city, :zip_code, :address_type, :account_id, :is_default
-
]
-
-
end
-
end
-
1
module AccountBlock
-
1
class ValidateAvailableSerializer
-
1
include FastJsonapi::ObjectSerializer
-
-
1
attributes :id, :activated
-
-
1
set_id do |object|
-
2
object.class.name.underscore
-
end
-
-
1
attribute :phone_number do |object|
-
2
object.full_phone_number
-
end
-
-
1
attribute :account_exists do |object|
-
2
object.id.present? ? true : false
-
end
-
end
-
end
-
1
module BuilderBase
-
1
class BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
-
1
class << self
-
1
private
-
-
1
def base_url
-
ENV['BASE_URL'] || 'http://localhost:3000'
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class BrandSerializer < BuilderBase::BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
1
attributes :id, :brand_name,:brand_name_arabic,:brand_website,:brand_year, :account_id
-
-
1
attributes :branding_tradmark_certificate do |object|
-
89
if object.branding_tradmark_certificate.attached?
-
8
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.branding_tradmark_certificate, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.branding_tradmark_certificate, only_path: true)
-
end
-
end
-
-
1
attribute :brand_image do |object|
-
89
if object.brand_image.attached?
-
88
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.brand_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.brand_image, only_path: true)
-
end
-
end
-
-
1
attributes :approve,:restricted,:gated, :created_at, :updated_at
-
-
1
attributes :store do |object|
-
89
BxBlockStoreManagement::StoreSerializer.new(object.store).serializable_hash
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueContentSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :custom_field_name, :value, :custom_field_id, :catalogue_id, :status
-
-
# attributes :catalogue do |object|
-
# if object.catalogue
-
# object.catalogue.serializable_hash(only: [:id, :sku, :besku])
-
# end
-
# end
-
-
1
attributes :custom_field_detail do |object|
-
7
if object.custom_field
-
7
BxBlockCategories::CustomFieldSerializer.new(object.custom_field)
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueOfferSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :price_info, :sale_price, :barcode_id, :bar_code_info, :sale_schedule_from, :sale_schedule_to, :warranty, :comments, :status
-
-
1
attributes :barcode do |object|
-
3
if object.barcode
-
3
object.barcode.serializable_hash(only: [:id, :bar_code])
-
end
-
end
-
-
1
attributes :catalogue do |object|
-
3
if object.catalogue
-
3
object.catalogue.serializable_hash(only: [:sku, :besku])
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :category_id, :brand_id, :parent_catalogue_id, :warehouse_id, :seller_id ,:sku,:besku, :bibc,:product_title, :is_variant, :fulfilled_type, :product_type, :purchased_count,:recommended_priority, :stocks, :content_status, :status, :stroked_price, :offer_percentage
-
-
1
attributes :product_image do |object|
-
259
if object.product_image.attached?
-
259
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.product_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.product_image, only_path: true)
-
end
-
end
-
-
1
attributes :created_at,:updated_at
-
-
1
attributes :final_price do |object|
-
259
object.calculate_effective_price.to_s
-
end
-
-
1
attributes :category do |object|
-
259
if object.category
-
259
object.category.serializable_hash(only: [:id, :name])
-
end
-
end
-
-
1
attributes :sub_category do |object|
-
259
if object.sub_category
-
94
object.sub_category.serializable_hash(only: [:id, :name])
-
end
-
end
-
-
1
attributes :mini_category do |object|
-
259
if object.mini_category
-
94
object.mini_category.serializable_hash(only: [:id, :name])
-
end
-
end
-
-
1
attributes :micro_category do |object|
-
259
if object.micro_category
-
108
object.micro_category.serializable_hash(only: [:id, :name])
-
end
-
end
-
-
1
attributes :brand do |object|
-
259
if object.brand
-
{
-
259
id: object.brand.id,
-
brand_name: object.brand.brand_name,
-
store: store_details(object.brand.store)
-
}
-
end
-
end
-
-
1
attributes :product_rating do |object|
-
259
reviews = object.review_and_ratings.approved_reviews.where(review_type: 'product')
-
259
total_count = reviews.count
-
259
if reviews.present?
-
{
-
64
average_rating: average_rating(reviews).round(1),
-
total_reviews: total_count
-
}
-
end
-
end
-
-
1
attributes :product_content do |object|
-
259
if object.product_content
-
143
product_content = object.product_content
-
{
-
143
product_attributes: product_content&.serializable_hash(only: [:id, :catalogue_id, :gtin, :unique_psku, :brand_name, :product_title, :mrp, :retail_price, :long_description, :whats_in_the_package, :country_of_origin, :product_color, :warranty_days, :warranty_months]),
-
size_and_capacity: product_content.size_and_capacity&.serializable_hash(only: [:size, :size_unit, :capacity, :capacity_unit, :hs_code, :prod_model_name, :prod_model_number, :number_of_pieces]),
-
shipping_detail: product_content.shipping_detail&.serializable_hash(only: [:shipping_length, :shipping_length_unit, :shipping_height, :shipping_height_unit, :shipping_width, :shipping_width_unit, :shipping_weight, :shipping_weight_unit]),
-
image_urls: image_urls(object, product_content),
-
195
feature_bullets: product_content.feature_bullets&.map { |bullet| bullet.serializable_hash(only: [:field_name, :value]) },
-
96
custom_fields_contents: object.catalogue_contents.map {|content| content.serializable_hash(only: [:id, :custom_field_name, :value,:custom_field_id, :catalogue_id] ) }
-
# special_features: product_content.special_features&.map { |feature| feature.serializable_hash(only: [:field_name, :value]) }
-
}
-
end
-
end
-
-
1
attributes :catalogue_offer do |object|
-
259
if object.catalogue_offer
-
7
object.catalogue_offer.serializable_hash(only: [:id, :price_info, :sale_price, :bar_code_info, :sale_schedule_from, :sale_schedule_to, :warranty, :comments, :status])
-
end
-
end
-
-
1
attributes :barcode do |object|
-
259
if object.barcode
-
object.barcode.serializable_hash(only: [:id, :bar_code])
-
end
-
end
-
-
1
attributes :deals do |object|
-
259
if object.deals
-
296
object.deals&.map { |deal| deal.serializable_hash(only: [:id, :deal_name, :deal_code,:discount_type,:discount_value, :start_date, :end_date, :status]) }
-
end
-
end
-
-
1
attributes :deal_catalogues do |object|
-
259
if object.deal_catalogues
-
296
object.deal_catalogues&.map { |seller_deal| seller_deal.serializable_hash(only: [:id, :deal_id, :catalogue_id,:seller_id, :seller_sku, :product_title, :seller_price, :current_offer_price, :deal_price, :status]) }
-
end
-
end
-
-
1
attributes :warehouses do |object|
-
259
if object.warehouses
-
270
object.warehouses.map {|warehouse| warehouse.serializable_hash(only: [:id, :warehouse_name]) }
-
end
-
end
-
-
1
attributes :warehouse_catalogues do |object|
-
270
object.warehouse_catalogues.map { |war_cat| war_cat.serializable_hash(only: [:id, :warehouse_id, :product_variant_group_id, :catalogue_id, :stocks]) }
-
end
-
-
1
attribute :seller do |object|
-
259
if object.seller
-
209
AccountBlock::AccountSerializer.new(object.seller)
-
end
-
end
-
-
1
attributes :product_variant_groups do |object|
-
259
if object&.product_variant_groups&.present?
-
25
object&.product_variant_groups&.map do |prod_variant|
-
{
-
29
id: prod_variant&.id,
-
product_sku: prod_variant&.product_sku,
-
product_besku: prod_variant&.product_besku,
-
product_bibc: prod_variant&.product_bibc,
-
group_attributes: prod_variant&.group_attributes&.group_by(&:attribute_name).map do |attribute_name, groups|
-
{
-
27
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
}
-
end
-
end
-
end
-
-
1
attributes :variant_products do |object|
-
259
CatalogueSerializer.new(object.variant_products)
-
end
-
-
1
attributes :variant_product_group do |object|
-
259
prod_variant = object.product_variant_group
-
259
if prod_variant
-
{
-
10
id: prod_variant.id,
-
product_sku: prod_variant.product_sku,
-
product_besku: prod_variant.product_besku,
-
product_bibc: prod_variant&.product_bibc,
-
group_attributes: prod_variant.group_attributes.order(created_at: :desc).map do |group|
-
{
-
12
id: group.id,
-
attribute_name: group.attribute_name,
-
options: group.option,
-
variant_attribute_id: group.variant_attribute_id,
-
attribute_option_id: group.attribute_option_id
-
}
-
end
-
}
-
end
-
end
-
-
1
def self.image_urls(object, product_content)
-
143
image_urls = [object.product_image.attached? ? (ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.product_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.product_image, only_path: true)) : nil] + (product_content.image_urls&.map(&:url) || [])
-
143
image_urls.compact
-
end
-
-
1
def self.average_rating(reviews)
-
64
total_reviews = reviews.count
-
64
return 0 if total_reviews.zero?
-
-
64
total_rating = reviews.sum(&:rating)
-
64
total_rating.to_f / total_reviews
-
end
-
-
1
def self.store_details(store)
-
259
return unless store
-
-
{
-
id: store.id,
-
store_name: store.store_name,
-
store_year: store.store_year,
-
store_url: store.store_url,
-
website_social_url: store.website_social_url,
-
approve: store.approve
-
}
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CatalogueVariantSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :seller_id,:micro_category_id, :group_name, :created_at, :updated_at
-
-
1
attributes :variant_attributes do |object|
-
6
if object.variant_attributes
-
6
object.variant_attributes.order(created_at: :desc).map do |var_attr|
-
{
-
5
id: var_attr.id,
-
attribute_name: var_attr.attribute_name,
-
attribute_options: var_attr.attribute_options.order(created_at: :desc)&.map do |attr_option|
-
{
-
7
id: attr_option.id,
-
option: attr_option.option
-
}
-
end
-
}
-
end
-
end
-
end
-
-
1
attributes :micro_category do |object|
-
6
BxBlockCategories::MicroCategorySerializer.new(object.micro_category)
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class DealCatalogueSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :deal_id, :catalogue_id,:seller_id, :seller_sku, :product_title, :seller_price, :current_offer_price, :deal_price, :status, :created_at,:updated_at
-
-
1
attribute :seller do |object|
-
8
AccountBlock::AccountSerializer.new(object.seller)
-
end
-
-
1
attributes :deal do |object|
-
8
if object.deal
-
8
DealSerializer.new(object.deal)
-
end
-
end
-
-
1
attribute :catalogue_full_details do |object|
-
8
if object.catalogue
-
8
CatalogueSerializer.new(object.catalogue)
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class DealSerializer < BuilderBase::BaseSerializer
-
-
1
attributes :id, :deal_name, :deal_code,:discount_type,:discount_value, :start_date, :end_date, :status, :created_at, :updated_at
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class GatedBrandSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :brand_id
-
-
1
attributes :reseller_permit_document do |object|
-
3
if object.reseller_permit_document.attached?
-
3
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.reseller_permit_document, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.reseller_permit_document, only_path: true)
-
end
-
end
-
-
1
attributes :approved, :created_at, :updated_at
-
-
1
attribute :brand do |object|
-
3
if object.brand
-
3
BrandSerializer.new(object.brand).serializable_hash
-
end
-
end
-
-
1
attributes :catalogues do |object|
-
3
if object.brand&.catalogues
-
3
object.brand.catalogues.map(&:serializable_hash)
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ParentCatalogueSerializer < BuilderBase::BaseSerializer
-
1
attributes :category_id, :brand_id, :product_title, :besku, :prod_model_no, :details, :status, :sku,
-
:sub_category_id, :mini_category_id, :micro_category_id
-
-
1
attributes :product_image do |object|
-
2
if object.product_image.attached?
-
2
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.product_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.product_image, only_path: true)
-
end
-
end
-
-
1
attributes :created_at,:updated_at
-
-
1
attributes :category do |object|
-
2
if object.category
-
2
object.category.serializable_hash(only: [:id, :name])
-
end
-
end
-
-
1
attributes :brand do |object|
-
2
if object.brand
-
2
object.brand.serializable_hash(only: [:id, :brand_name])
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ProductContentSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :catalogue_id, :gtin, :unique_psku, :brand_name, :product_title, :mrp, :retail_price, :long_description, :whats_in_the_package, :country_of_origin, :product_color, :warranty_days, :warranty_months, :dispenser_type, :scent_type, :target_use, :style_name
-
-
1
attribute :size_and_capacity do |object|
-
5
object.size_and_capacity&.serializable_hash(only: [:id, :size, :size_unit, :capacity, :capacity_unit, :hs_code, :prod_model_name, :prod_model_number, :number_of_pieces])
-
end
-
-
1
attribute :shipping_detail do |object|
-
5
object.shipping_detail&.serializable_hash(only: [:id, :shipping_length, :shipping_length_unit, :shipping_height, :shipping_height_unit, :shipping_width, :shipping_width_unit, :shipping_weight, :shipping_weight_unit])
-
end
-
-
1
attribute :image_urls do |object|
-
32
object.image_urls&.map {|image| image.serializable_hash(only: [:id, :url])}
-
end
-
-
1
attribute :feature_bullets do |object|
-
14
object.feature_bullets&.map { |bullet| bullet.serializable_hash(only: [:id, :field_name, :value]) }
-
end
-
-
1
attributes :custom_fields_contents do |object|
-
25
object.catalogue.catalogue_contents.order(created_at: :asc)&.map {|content| content.serializable_hash(only: [:id, :custom_field_name, :value,:custom_field_id, :catalogue_id] ) }
-
end
-
-
1
attribute :special_features do |object|
-
9
object.special_features&.map { |feature| feature.serializable_hash(only: [:id, :field_name, :value]) }
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ProductVariantGroupSerializer < BuilderBase::BaseSerializer
-
1
attributes :id,:catalogue_variant_id, :catalogue_id, :variant_product_id, :product_sku,:product_besku, :product_bibc, :product_description, :price, :product_title, :created_at, :updated_at
-
-
1
attributes :group_attributes do |object|
-
5
if object.group_attributes
-
5
object.group_attributes.group_by(&:attribute_name).map do |attribute_name, groups|
-
{
-
7
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
end
-
end
-
-
1
attributes :individual_group_attr_with_ids do |object|
-
5
if object.group_attributes
-
5
object.group_attributes.order(created_at: :desc).map do |group|
-
{
-
10
id: group.id,
-
attribute_name: group.attribute_name,
-
options: group.option,
-
variant_attribute_id: group.variant_attribute_id,
-
attribute_option_id: group.attribute_option_id
-
}
-
end
-
end
-
end
-
-
1
attribute :variant_product do |object|
-
5
BxBlockCatalogue::CatalogueSerializer.new(object.variant_product)
-
end
-
-
1
attribute :catalogue do |object|
-
5
BxBlockCatalogue::CatalogueSerializer.new(object.catalogue)
-
end
-
-
1
attribute :catalogue_variant do |object|
-
5
BxBlockCatalogue::CatalogueVariantSerializer.new(object.catalogue_variant)
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class RestrictedBrandSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :brand_id, :seller_id
-
-
1
attributes :reseller_permit_document do |object|
-
3
if object.reseller_permit_document.attached?
-
3
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.reseller_permit_document, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.reseller_permit_document, only_path: true)
-
end
-
end
-
-
1
attributes :approved, :created_at, :updated_at
-
-
1
attribute :brand do |object|
-
3
if object.brand
-
3
BrandSerializer.new(object.brand).serializable_hash
-
end
-
end
-
-
1
attributes :seller do |object|
-
3
if object.seller
-
3
object.seller&.serializable_hash
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ReviewSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :title, :rating, :description, :review_type, :is_approved, :order_item_id, :created_at, :updated_at, :helpful_count
-
-
1
attribute :review_images do |object|
-
13
if object.review_images.attached?
-
object.review_images.map { |image| "#{ENV['BASE_URL']}#{Rails.application.routes.url_helpers.rails_blob_path(image, only_path: true)}" }
-
end
-
end
-
-
1
attribute :helpful do |object, params|
-
13
current_account = params[:current_account]
-
{
-
26
helpful_by_current_user: current_account.present? ? object.helpful_by?(current_account) : false,
-
data: object.helpful_reviews.find_by(customer_id: current_account&.id)
-
}
-
end
-
-
1
attribute :catalogue do |obj|
-
13
BxBlockCatalogue::Catalogue.find_by(id: obj&.catalogue_id)
-
end
-
-
1
attribute :reviewer do |obj|
-
13
AccountBlock::AccountSerializer.new(AccountBlock::Account.find_by(id: obj&.reviewer_id))
-
end
-
-
1
attribute :account do |obj|
-
13
AccountBlock::Account.find_by(id: obj&.account_id)
-
end
-
-
1
attribute :order_item do |obj|
-
13
BxBlockShoppingCart::OrderItem.find_by(id: obj.order_item_id)
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class StoreFrontListingSerializer < BuilderBase::BaseSerializer
-
1
attributes :description, :title, :rating
-
1
attributes :name do |object|
-
1
object.account.full_name
-
end
-
1
attributes :created_at do |object|
-
1
object.created_at.strftime("%d/%m/%y")
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class StoreFrontSerializer < BuilderBase::BaseSerializer
-
1
attributes :category_id, :brand_id,:warehouse_id, :sku, :besku, :product_title, :status
-
-
1
attributes :email do |object|
-
4
object.seller.email
-
end
-
1
attributes :phone_number do |object|
-
4
object.seller.phone_number
-
end
-
1
attributes :contact_number do |object|
-
4
object&.seller&.addresses&.first&.contact_number
-
end
-
1
attributes :state do |object|
-
4
object&.seller&.addresses&.first&.state
-
end
-
1
attributes :city do |object|
-
4
object&.seller&.addresses&.first&.city
-
end
-
1
attributes :reviews do |object|
-
4
ReviewSerializer.new(object.review_and_ratings).serializable_hash[:data]
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class WarehouseCatalogueSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :warehouse_id, :product_variant_group_id, :catalogue_id, :stocks, :created_at, :updated_at
-
-
1
attributes :catalogue do |object|
-
10
if object.catalogue
-
10
CatalogueSerializer.new(object.catalogue)
-
end
-
end
-
-
1
attribute :selected_product_variant do |object|
-
10
if object.product_variant_group.present?
-
{
-
7
id: object.product_variant_group.id,
-
product_sku: object.product_variant_group.product_sku,
-
product_besku: object.product_variant_group.product_besku,
-
group_attributes: object.product_variant_group.group_attributes&.group_by(&:attribute_name).map do |attribute_name, groups|
-
{
-
2
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
}
-
end
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class WarehouseSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :warehouse_name, :warehouse_address_1,:warehouse_address_2, :contact_number, :contact_person, :processing_days, :account_id, :created_at, :updated_at
-
-
1
attribute :seller do |object|
-
7
AccountBlock::AccountSerializer.new(object.account)
-
end
-
-
1
attributes :stock_logs do |object|
-
7
if object.warehouse_catalogues
-
7
WarehouseCatalogueSerializer.new(object.warehouse_catalogues)
-
end
-
end
-
-
1
attributes :product_variant_groups do |object|
-
7
if object.product_variant_groups
-
7
object.product_variant_groups.map do |product_variant_group|
-
{
-
1
id: product_variant_group.id,
-
catalogue_id: product_variant_group.catalogue_id,
-
product_sku: product_variant_group.product_sku,
-
product_besku: product_variant_group.product_besku,
-
group_attributes: product_variant_group.group_attributes&.group_by(&:attribute_name).map do |attribute_name, groups|
-
{
-
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
}
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class CategorySerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :name, :rank, :created_at, :updated_at
-
-
1
attributes :category_image do |object|
-
38
if object.category_image.attached?
-
38
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.category_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.category_image, only_path: true)
-
end
-
end
-
-
1
attributes :header_image do |object|
-
38
if object.header_image.attached?
-
38
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.header_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.header_image, only_path: true)
-
end
-
end
-
-
1
attributes :sub_categories do |object, params|
-
38
object.sub_categories.map do |sub_category|
-
{
-
11
id: sub_category.id,
-
name: sub_category.name,
-
mini_categories: sub_category.mini_categories.map do |minicategory|
-
{
-
12
id: minicategory.id,
-
name: minicategory.name,
-
micro_categories: minicategory.micro_categories.map do |microcategory|
-
{
-
14
id: microcategory.id,
-
name: microcategory.name
-
}
-
end
-
}
-
end
-
}
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class CustomFieldSerializer < BuilderBase::BaseSerializer
-
1
attributes :field_name, :mandatory
-
-
1
attributes :custom_fields_options do |object|
-
16
object.custom_fields_options.map(&:option_name)
-
end
-
-
1
attribute :category do |object|
-
16
object.fieldable if object.fieldable_type == "BxBlockCategories::Category"
-
end
-
-
1
attribute :sub_category do |object|
-
16
object.fieldable if object.fieldable_type == "BxBlockCategories::SubCategory"
-
end
-
-
1
attribute :mini_category do |object|
-
16
object.fieldable if object.fieldable_type == "BxBlockCategories::MiniCategory"
-
end
-
-
1
attribute :micro_category do |object|
-
16
object.fieldable if object.fieldable_type == "BxBlockCategories::MicroCategory"
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class MicroCategorySerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :name, :mini_category_id
-
-
1
attribute :sub_category_id do |object|
-
13
object.mini_category.sub_category.id
-
end
-
-
1
attribute :category_id do |object|
-
13
object.mini_category.sub_category.category.id
-
end
-
-
1
attributes :relation do |object|
-
13
if object.present?
-
13
"#{object.mini_category.sub_category.category.name} >> #{object.mini_category.sub_category.name} >> #{object.mini_category.name}"
-
end
-
end
-
-
1
attributes :created_at, :updated_at
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class MiniCategorySerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :name, :sub_category_id
-
-
1
attributes :relation do |object|
-
5
if object.present?
-
5
"#{object.sub_category.category.name} >> #{object.sub_category.name}"
-
end
-
end
-
-
1
attributes :created_at, :updated_at
-
-
1
attributes :micro_categories do |object|
-
5
object.micro_categories.map do |micro_category|
-
{
-
6
id: micro_category.id,
-
name: micro_category.name,
-
relation: "#{object.sub_category.category.name} >> #{object.sub_category.name} >> #{object.name}",
-
}
-
end
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class SubCategorySerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :name, :parent_id, :created_at, :updated_at
-
-
1
attributes :relation do |object|
-
6
object.category.name
-
end
-
-
1
attributes :mini_categories do |object, params|
-
6
object.mini_categories.map do |mini_category|
-
{
-
8
id: mini_category.id,
-
name: mini_category.name,
-
micro_categories: mini_category.micro_categories.map do |microcategory|
-
{
-
8
id: microcategory.id,
-
name: microcategory.name
-
}
-
end
-
}
-
end
-
end
-
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ContactSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:title,
-
:email,
-
:description,
-
:contact_type,
-
:created_at,
-
]
-
1
attributes :image do |object|
-
1
if object.image.attached?
-
1
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.image, only_path: true)
-
end
-
end
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class CouponCodeSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:id,
-
:title,
-
:description,
-
:code,
-
:discount_type,
-
:discount,
-
:valid_from,
-
:valid_to,
-
:min_cart_value,
-
:max_cart_value,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class SubscribeCouponSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:id,
-
:account_id,
-
:coupon_code_id,
-
:catalogue_id,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
1
module BxBlockDashboard
-
1
class AuthorFavoriteBookSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :title,:status, :created_at, :updated_at
-
-
1
attributes :catalogues do |object|
-
5
if object.favorite_book_catalogues.present?
-
5
object.favorite_book_catalogues.map do |tps|
-
40
BxBlockCatalogue::CatalogueSerializer.new(tps.catalogue).serializable_hash
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class BannerSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :title, :description, :button_text, :button_link, :banner_type, :banner_group_id, :section
-
-
1
attributes :banner_image do |object|
-
6
if object.banner_image.attached?
-
5
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.banner_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.banner_image, only_path: true)
-
end
-
end
-
-
1
attributes :banner_group do |object|
-
6
if object.banner_group
-
4
object.banner_group.serializable_hash
-
end
-
end
-
-
1
attributes :catalogue do |object|
-
6
if object.catalogue.present?
-
1
BxBlockCatalogue::CatalogueSerializer.new(object.catalogue).serializable_hash
-
end
-
end
-
-
1
attributes :category do |object|
-
6
if object.category.present?
-
2
BxBlockCategories::CategorySerializer.new(object.category).serializable_hash
-
end
-
end
-
-
1
attributes :sub_category do |object|
-
6
if object.sub_category.present?
-
1
BxBlockCategories::SubCategorySerializer.new(object.sub_category).serializable_hash
-
end
-
end
-
-
1
attributes :deal do |object|
-
6
if object.deal.present?
-
1
BxBlockCatalogue::DealSerializer.new(object.deal).serializable_hash
-
end
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class HeaderCategorySerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :sequence_no, :category_id, :created_at, :updated_at
-
-
1
attributes :category do |object|
-
5
category = object.category
-
5
if category
-
{
-
5
"id": category.id,
-
"name": category.name,
-
"created_at": category.created_at,
-
"updated_at": category.updated_at,
-
5
"header_image": ((ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(category.header_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(category.header_image, only_path: true)) if category.header_image.attached?),
-
5
"category_image": ((ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(category.category_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(category.category_image, only_path: true)) if category.category_image.attached?),
-
}
-
end
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class MostPopularCategorySerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :sequence_no, :category_id, :created_at, :updated_at
-
-
1
attributes :category do |object|
-
5
if object.category
-
5
object.category.serializable_hash
-
end
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TopBrandSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :sequence_no, :brand_id, :created_at, :updated_at
-
-
1
attributes :brand do |object|
-
5
if object.brand
-
5
object.brand.serializable_hash
-
end
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class TrendingProductSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :slider, :created_at, :updated_at
-
-
1
attribute :sale_ad_image do |image|
-
3
if image.sale_ad_image.attached?
-
3
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(image.sale_ad_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(image.sale_ad_image, only_path: true)
-
end
-
end
-
1
attributes :catalogues do |object|
-
3
if object.trending_product_selections.present?
-
3
object.trending_product_selections.map do |tps|
-
18
BxBlockCatalogue::CatalogueSerializer.new(tps.catalogue).serializable_hash
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockDashboard
-
1
class WeeklyHomieeDealSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :start_time, :end_time, :status, :created_at, :updated_at
-
-
1
attribute :weekly_deals do |object|
-
3
object.weekly_deals.map do |wd|
-
{
-
9
id: wd.id,
-
caption: wd.caption,
-
discount_percent: wd.discount_percent,
-
url: wd.url,
-
bg_image: self.bg_image_url(wd),
-
deal: wd.deal&.serializable_hash
-
}
-
end
-
end
-
-
1
private
-
-
1
def self.bg_image_url(wd)
-
9
if wd.bg_image.attached?
-
9
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(wd.bg_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(wd.bg_image, only_path: true)
-
end
-
end
-
end
-
end
-
1
module BxBlockFavourites
-
1
class FavouriteSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:favouriteable_id,
-
:favouriteable_type,
-
:user_id,
-
:created_at,
-
:updated_at,
-
]
-
-
1
attributes :catalogue do |object|
-
5
if object.favouriteable.is_a?(BxBlockCatalogue::Catalogue)
-
5
BxBlockCatalogue::CatalogueSerializer.new(object.favouriteable).serializable_hash
-
end
-
end
-
-
1
attribute :selected_product_variant do |object|
-
5
if object.product_variant_group.present?
-
{
-
1
id: object.product_variant_group.id,
-
product_sku: object.product_variant_group.product_sku,
-
product_besku: object.product_variant_group.product_besku,
-
product_description: object.product_variant_group.product_description,
-
price: object.product_variant_group.price,
-
product_title: object.product_variant_group.product_title,
-
1
product_images: object.product_variant_group.product_images.attached? ? object.product_variant_group.product_images.map { |image| "#{ENV['BASE_URL']}#{Rails.application.routes.url_helpers.rails_blob_path(image, only_path: true)}" } : nil,
-
group_attributes: object.product_variant_group.group_attributes&.group_by(&:attribute_name).map do |attribute_name, groups|
-
{
-
attribute_name: attribute_name,
-
options: groups.map(&:option)
-
}
-
end
-
}
-
end
-
end
-
end
-
end
-
1
module BxBlockInvoicebilling
-
1
class InvoiceBillingSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :invoice_number, :order_id, :order_item_id, :customer_id, :created_at, :updated_at
-
-
1
attributes :invoice_pdf do |object|
-
1
if object.invoice_pdf.attached?
-
1
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.invoice_pdf, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.invoice_pdf, only_path: true)
-
end
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class DeliveryRequestSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :warehouse_id, :warehouse_name, :seller_id, :order_id, :order_number, :address_1, :address_2, :status, :created_at, :updated_at
-
-
1
attribute :sellers do |object|
-
3
AccountBlock::AccountSerializer.new(object.seller)
-
end
-
-
1
attribute :warehouse do |object|
-
3
BxBlockCatalogue::WarehouseSerializer.new(object.warehouse)
-
end
-
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class OrderStatusSerializer < BuilderBase::BaseSerializer
-
1
attributes :name, :created_at, :updated_at
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class StockIntakeSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :stock_value, :stock_qty, :ship_date, :receiving_date, :status, :created_at, :updated_at
-
-
1
attribute :seller do |object|
-
5
AccountBlock::AccountSerializer.new(object.seller)
-
end
-
-
1
attribute :catalogue do |object|
-
5
BxBlockCatalogue::CatalogueSerializer.new(object.catalogue)
-
end
-
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class ProductViewSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:id,
-
:catalogue_id,
-
:user_id,
-
:viewed_at,
-
:created_at,
-
:updated_at
-
]
-
-
1
attribute :buyer do |object|
-
2
AccountBlock::AccountSerializer.new(object.user).serializable_hash
-
end
-
-
1
attribute :catalogue do |object|
-
2
BxBlockCatalogue::CatalogueSerializer.new(object.catalogue).serializable_hash
-
end
-
-
end
-
end
-
1
module BxBlockSeoSetting
-
1
class SeoSettingSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:id,
-
:page_name,
-
:meta_title,
-
:meta_description,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class OrderItemSerializer < BuilderBase::BaseSerializer
-
-
1
attributes *[
-
:id,
-
:order_id,
-
:price,
-
:quantity,
-
:discount_price,
-
:taxable,
-
:taxable_value,
-
:accepted
-
]
-
-
1
attribute :order_status do |object|
-
22
BxBlockOrderManagement::OrderStatusSerializer.new(object.order_status)
-
end
-
-
1
attribute :item do |object|
-
{
-
22
catalogue: BxBlockCatalogue::CatalogueSerializer.new(object.catalogue),
-
22
selected_product_variant: if object.product_variant_group.present?
-
{
-
2
id: object.product_variant_group.id,
-
product_sku: object.product_variant_group.product_sku,
-
product_besku: object.product_variant_group.product_besku,
-
group_attributes: object.product_variant_group.group_attributes&.group_by(&:attribute_name).map do |attr_name, groups|
-
{
-
2
attribute_name: attr_name,
-
options: groups.map(&:option)
-
}
-
end
-
}
-
end,
-
favourite: BxBlockShoppingCart::OrderItem.get_favourites(object)
-
}
-
end
-
-
1
attribute :return_reason_details do |object|
-
22
object.return_reason_details.map do |rrd|
-
rrd.serializable_hash
-
end
-
end
-
-
1
attribute :return_exchange_requests do |object|
-
22
object.return_exchange_requests.map do |rer|
-
rer.serializable_hash
-
end
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class OrderSerializer < BuilderBase::BaseSerializer
-
1
extend BxBlockShoppingCart::OrderConcern
-
-
1
attributes *[
-
:id,
-
:order_number,
-
:status,
-
:total_fees,
-
:total_items,
-
:discount,
-
:total_tax,
-
:final_price,
-
:order_placed_at,
-
:delivered_at,
-
:accepted,
-
:created_at,
-
:updated_at
-
]
-
-
1
attribute :order_status do |object|
-
17
BxBlockOrderManagement::OrderStatusSerializer.new(object.order_status)
-
end
-
-
1
attribute :order_items do |object|
-
17
BxBlockShoppingCart::OrderItemSerializer.new(object.order_items.order(created_at: :desc))
-
end
-
-
1
attribute :customer do |object|
-
17
AccountBlock::AccountSerializer.new(object.customer)
-
end
-
-
1
attribute :shipping_address do |object|
-
17
get_delivery_address(object)
-
end
-
-
1
attribute :shipped_order_details do |object|
-
17
if object.shipped_order_details
-
17
object.shipped_order_details.order(created_at: :desc).map do |shipped_order_detail|
-
{
-
id: shipped_order_detail.id,
-
shipping_details: shipped_order_detail.shipping_details,
-
order_id: shipped_order_detail.order_id
-
}
-
end
-
end
-
end
-
-
1
attribute :coupon_code do |object|
-
17
BxBlockCouponCg::CouponCodeSerializer.new(object.coupon_code)
-
end
-
-
# attribute :sellers do |object|
-
# AccountBlock::AccountSerializer.new(object.sellers)
-
# end
-
-
# class << self
-
# def order_services_for order
-
# order.sub_categories.pluck(:name)
-
# # order.services.map{|service| service.sub_category.name }
-
# end
-
# end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreDashboardSectionSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :store_id, :section_name, :section_type, :banner_name, :banner_url, :created_at, :updated_at
-
-
1
attributes :banner_image do |object|
-
17
if object.banner_image.attached?
-
16
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.banner_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.banner_image, only_path: true)
-
end
-
end
-
-
1
attributes :store_section_grids do |object|
-
17
if object.store_section_grids
-
17
object.store_section_grids.order(created_at: :asc).map do |store_section_grid|
-
11
BxBlockStoreManagement::StoreSectionGridSerializer.new(store_section_grid).serializable_hash
-
end
-
end
-
end
-
-
# attribute :store do |object|
-
# object.store.serializable_hash
-
# end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreMenuSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :store_name, :title, :banner_name, :position, :product_quantity, :created_at, :updated_at
-
-
1
attributes :logo do |object|
-
4
if object.logo.attached?
-
3
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.logo, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.logo, only_path: true)
-
end
-
end
-
-
1
attributes :cover_image do |object|
-
4
if object.cover_image.attached?
-
1
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.cover_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.cover_image, only_path: true)
-
end
-
end
-
-
1
attribute :store do |object|
-
4
object.store.serializable_hash
-
end
-
-
1
attributes :catalogues do |object|
-
4
if object.catalogues
-
4
object.catalogues.map do |catalogue|
-
8
BxBlockCatalogue::CatalogueSerializer.new(catalogue).serializable_hash
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreSectionGridSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :store_dashboard_section_id, :grid_name, :grid_no, :grid_image, :grid_url, :created_at, :updated_at
-
-
1
attributes :grid_image do |object|
-
15
if object.grid_image.attached?
-
13
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.grid_image, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.grid_image, only_path: true)
-
end
-
end
-
end
-
end
-
1
module BxBlockStoreManagement
-
1
class StoreSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :store_name, :store_year, :store_url, :website_social_url, :approve, :created_at, :updated_at
-
-
1
attributes :store_menus do |object|
-
32
if object.store_menus
-
44
object.store_menus.order(position: :asc).map {|menu| menu.serializable_hash}
-
end
-
end
-
-
1
attributes :brand_trade_certificate do |object|
-
32
if object.brand_trade_certificate.attached?
-
32
ENV['BASE_URL'] ? (ENV['BASE_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.brand_trade_certificate, only_path: true)) : Rails.application.routes.url_helpers.rails_blob_path(object.brand_trade_certificate, only_path: true)
-
end
-
end
-
-
1
attributes :store_dashboard_sections do |object|
-
32
if object.store_dashboard_sections
-
44
object.store_dashboard_sections.order(created_at: :asc).map { |store_dashboard_section| BxBlockStoreManagement::StoreDashboardSectionSerializer.new(store_dashboard_section).serializable_hash }
-
end
-
end
-
-
1
attribute :brand do |object|
-
32
object.brand&.serializable_hash
-
end
-
-
1
attribute :account do |object|
-
32
AccountBlock::AccountSerializer.new(object.account)
-
end
-
-
end
-
end
-
1
module BxBlockTermsandconditions
-
1
class PrivacyAndLegalPolicySerializer < BuilderBase::BaseSerializer
-
-
1
attributes :title, :content, :status
-
end
-
end
-
1
module AccountBlock
-
1
class EmailValidation
-
1
include ActiveModel::Validations
-
-
1
attr_reader :email
-
-
1
class << self
-
1
def regex
-
1
/[^@]+@\S+[.]\S+/
-
end
-
-
1
def regex_string
-
regex.to_s.sub("(?-mix:", "").delete_suffix(")")
-
end
-
end
-
-
1
validates :email, format: {
-
with: regex,
-
multiline: true
-
}
-
-
1
def initialize(email)
-
8
@email = email
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class PasswordValidation
-
1
include ActiveModel::Validations
-
-
1
attr_reader :password
-
-
1
class << self
-
1
def regex
-
# ^ Start anchor
-
# (?=.*[A-Z]) Has one uppercase letter
-
# (?=.*[!@#$&*?<>',\[\]}{=\-)(^%`~+.:;_]) Has one special case symbol
-
# (?=.*[0-9]) Has one digit
-
# (?=.*[a-z]) Has one lowercase letter
-
# .{8,} Is at least length 8
-
# $ End anchor
-
1
/^(?=.*[A-Z])(?=.*[#!@$&*?<>',\[\]}{=\-)(^%`~+.:;_])(?=.*[0-9])(?=.*[a-z]).{8,}$/
-
end
-
-
1
def regex_string
-
regex.to_s.sub("(?-mix:", "").delete_suffix(")")
-
end
-
-
1
def rules
-
"Password should be a minimum of 8 characters long," \
-
" contain both uppercase and lowercase characters, at" \
-
" least one digit, and one special character " \
-
'(!@#$&*?<>\',[]}{=-)(^%`~+.:;_).'
-
end
-
end
-
-
1
validates :password, format: {
-
with: regex,
-
multiline: true
-
}
-
-
1
def initialize(password)
-
2
@password = password
-
end
-
end
-
end
-
1
module BuilderJsonWebToken
-
1
class JsonWebToken
-
1
attr_reader :id, :expiration
-
-
1
class << self
-
1
def encode(id, data = {}, expiration = nil)
-
494
expiration, data = data, expiration unless data.is_a?(Hash)
-
-
494
data ||= {}
-
494
expiration ||= 24.hours.from_now
-
-
494
payload = build_payload_for(id.to_i, data, expiration.to_i)
-
-
494
JWT.encode payload, secret_key, algorithm
-
end
-
-
1
def decode(token)
-
372
JsonWebToken.new token_data_for(token)
-
end
-
-
1
private
-
-
1
def token_data_for(token)
-
372
JWT.decode(token, secret_key, false, {
-
:algorithm => algorithm,
-
})[0]
-
end
-
-
1
def build_payload_for(id, data, expiration)
-
{
-
494
:id => id,
-
:exp => expiration,
-
}.merge(data)
-
end
-
-
1
def secret_key
-
866
@secret_key ||= ENV['SECRET_KEY_BASE']
-
end
-
-
1
def algorithm
-
866
'HS512'
-
end
-
end
-
-
1
def initialize(data)
-
371
@id = data.delete('id')
-
371
@expiration = Time.at(data.delete('exp')).to_time
-
371
@struct = nil
-
371
initialize_attributes_for data if data.is_a?(Hash) && data.keys.any?
-
end
-
-
1
private
-
-
1
def initialize_attributes_for(data)
-
288
@struct = Struct.new(*data.keys.map(&:to_sym)).new
-
288
data.keys.each do |key|
-
288
@struct.send("#{key}=", data[key])
-
end
-
end
-
-
1
def respond_to_missing?(method, *args)
-
6
super || @struct.respond_to?(method)
-
end
-
-
1
def method_missing(method, *args, &block)
-
return @struct.send(method) if @struct.respond_to?(method)
-
super
-
end
-
end
-
end
-
1
module BxBlockEmailNotifications
-
1
class SendEmailNotificationService < ApplicationMailer
-
-
1
def notification
-
63
@account = params[:account]
-
63
@host = Rails.env.development? ? "http://localhost:3000" : ENV['FE_URL']
-
63
@product = params[:product]
-
63
@otp = params[:pin]
-
63
@to = @account.present? ? @account.email : params[:to]
-
63
@order = params[:order]
-
63
@order_item = params[:order_item]
-
63
@wms_event = params[:wms_event]
-
63
@subject = params[:subject]
-
63
@contact = params[:contact]
-
63
@from = params[:from] ? params[:from] : "admin_notification@byezzy.com"
-
-
63
mailer_call(@from, @to, @subject, params[:file])
-
end
-
-
1
private
-
-
1
def mailer_call(from, to, subject, file)
-
63
mail(
-
to: to,
-
from: from,
-
subject: subject
-
) do |format|
-
126
format.html { render file }
-
end
-
end
-
end
-
end
-
1
require 'active_model'
-
-
1
module BxBlockPosts
-
1
module Validators
-
1
class BlobValidator < ActiveModel::EachValidator
-
1
def validate_each(record, attribute, values)
-
return unless values.attached?
-
-
Array(values).each do |value|
-
if options[:size_range].present?
-
if options[:size_range].min > value.blob.byte_size
-
record.errors.add(
-
attribute,
-
:min_size_error,
-
min_size: min_size_range
-
)
-
elsif options[:size_range].max < value.blob.byte_size
-
record.errors.add(
-
attribute,
-
:max_size_error,
-
max_size: max_size_range
-
)
-
end
-
end
-
-
unless valid_content_type?(value.blob)
-
record.errors.add(attribute, :content_type)
-
end
-
end
-
end
-
-
1
private
-
-
1
def min_size_range
-
ActiveSupport::NumberHelper.number_to_human_size(
-
options[:size_range].min
-
)
-
end
-
-
1
def max_size_range
-
ActiveSupport::NumberHelper.number_to_human_size(
-
options[:size_range].max
-
)
-
end
-
-
1
def valid_content_type?(blob)
-
return true if options[:content_type].nil?
-
-
case options[:content_type]
-
when Regexp
-
options[:content_type].match?(blob.content_type)
-
when Array
-
options[:content_type].include?(blob.content_type)
-
when Symbol
-
blob.public_send("#{options[:content_type]}?")
-
else
-
options[:content_type] == blob.content_type
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockProfile
-
1
class UpdateAccountValidator
-
1
include ActiveModel::Validations
-
-
ATTRIBUTES = [
-
1
[:first_name],
-
[:last_name],
-
[:new_phone_number, :full_phone_number],
-
[:new_password, :password],
-
[:new_email, :email],
-
]
-
-
1
attr_accessor(*ATTRIBUTES.map(&:first))
-
1
attr_accessor :current_password
-
-
1
validates :account, :presence => {:message => 'not found'}
-
1
validates :first_name, :presence => {:allow_nil => true}
-
1
validates :last_name, :presence => {:allow_nil => true}
-
1
validate :validate_phone_number
-
1
validate :validate_email
-
1
validate :validate_password
-
-
1
def initialize(account_id, params)
-
@account_id = account_id
-
-
@current_password = params[:current_password]
-
-
params.keys.each do |key|
-
self.send "#{key}=", params[key]
-
end
-
end
-
-
1
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
1
def attributes
-
return {} unless valid?
-
-
attrs = {}
-
-
ATTRIBUTES.each do |values|
-
source = values.first
-
dest = values.last
-
-
value = send(source)
-
attrs[dest] = value if value
-
end
-
-
attrs
-
end
-
-
1
private
-
-
1
def validate_phone_number
-
return unless new_phone_number
-
validator = ChangePhoneValidator.new(@account_id, new_phone_number)
-
validate_with_validator validator
-
end
-
-
1
def validate_password
-
return if !current_password && !new_password
-
-
validator = ChangePasswordValidator
-
.new(@account_id, current_password, new_password)
-
validate_with_validator validator
-
end
-
-
1
def validate_email
-
return unless new_email
-
validator = ChangeEmailValidator.new(@account_id, new_email)
-
validate_with_validator validator
-
end
-
-
1
def validate_with_validator(validator)
-
return if validator.valid?
-
-
validator.errors.each do |attr, message|
-
errors.add attr, message
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
module PatchUpdateAccountValidator
-
1
extend ActiveSupport::Concern
-
1
included do
-
ATTRIBUTES = [
-
1
[:first_name],
-
[:last_name],
-
%i[new_phone_number full_phone_number],
-
%i[new_password password],
-
%i[new_email email], [:activated], [:gender], [:age], [:date_of_birth], [:category_ids]
-
].freeze
-
-
1
attr_accessor(*ATTRIBUTES.map(&:first))
-
-
1
def initialize(account_id, params, image_data = {})
-
@account_id = account_id
-
@current_password = params[:current_password]
-
@image_data = image_data
-
if @image_data.present?
-
@image_content_type = @image_data["content_type"]
-
attach_image
-
end
-
params.each_key do |key|
-
send "#{key}=", params[key]
-
end
-
end
-
-
1
private
-
-
1
def attach_image
-
decoded_data = Base64.decode64(@image_data["data"].split(",")[1])
-
account.images.attach(
-
io: StringIO.new(decoded_data),
-
content_type: @image_data["content_type"],
-
filename: @image_data["filename"]
-
)
-
end
-
-
1
def image_validation
-
return unless account.images.attached? && @image_data.present?
-
if %w[image/jpeg image/jpg image/png].exclude?(@image_content_type)
-
account.images.last.purge
-
errors.add(:The_profile, "photo cannot be updated, the image is of unsupported type.")
-
return
-
end
-
set_default_image
-
end
-
-
1
def set_default_image
-
new_img = account.images.last
-
new_img.update(default_image: true)
-
ActiveStorage::Attachment.where(
-
record_type: "AccountBlock::Account", record_id: account.id
-
).where("id != ?", new_img.id).update(default_image: false)
-
end
-
end
-
end
-
end
-
1
module BxBlockSalesreporting
-
1
class SalesReportService
-
REPORT_TYPES = %w[
-
1
sales_report sales_and_traffic_report return_report compare_sales
-
].freeze
-
-
1
def initialize(start_date, end_date, report_type, seller = nil, sort_by = nil, sort_order = nil)
-
11
@start_date = start_date
-
11
@end_date = end_date
-
11
@report_type = report_type
-
11
@seller = seller
-
11
@sort_order = sort_order
-
11
@sort_by = sort_by
-
end
-
-
1
def call
-
11
report_data = case @report_type
-
when 'sales_report'
-
4
sales_report
-
when 'sales_and_traffic_report'
-
2
sales_and_traffic_report
-
when 'return_report'
-
2
return_report
-
when 'compare_sales'
-
2
compare_sales_report
-
else
-
1
{ error: 'Invalid report type' }
-
end
-
-
11
sort_report_data(report_data)
-
end
-
-
1
private
-
-
1
def sort_report_data(data)
-
11
return data unless @sort_by
-
-
2
data.sort_by! { |item| item[@sort_by.to_sym] }
-
-
1
data.reverse! if @sort_order == 'desc'
-
1
data
-
end
-
-
1
def sales_report
-
7
orders.group_by { |order| order.order_placed_at.to_date }.map do |order_placed_at, orders|
-
3
order_items = filter_order_items_by_seller(orders.flat_map(&:order_items))
-
6
catalogues = order_items.map { |item| item.catalogue }
-
3
sessions_total = calculate_sessions_total(catalogues)
-
3
seller_sessions_total = seller_catalogue_sessions
-
{
-
3
date: order_placed_at,
-
ordered_product_sales: ordered_product_sales(orders),
-
units_ordered: units_ordered(orders),
-
total_order_item: total_order_items(orders),
-
average_sales_per_order_item: average_sales_per_order_items(orders),
-
average_units_per_order_item: average_units_per_order_items(orders),
-
average_selling_price: average_selling_price(orders),
-
order_item_sessions_total: sessions_total,
-
order_item_session_percentage: calculate_session_percentage(sessions_total, seller_sessions_total)
-
}
-
end
-
end
-
-
1
def sales_and_traffic_report
-
2
seller_sessions_total = seller_catalogue_sessions
-
2
orders.flat_map(&:order_items).group_by(&:catalogue_id).map do |catalogue_id, order_items|
-
2
next if @seller && !@seller.catalogue_ids.include?(catalogue_id)
-
-
2
product = order_items.first.catalogue
-
2
sessions_total = calculate_sessions_total([product])
-
-
{
-
2
parent_besku: product.besku,
-
2
child_besku: product.product_variant_group ? product.product_variant_group.product_besku : "N/A",
-
title: product.product_title,
-
2
sku: product.product_variant_group ? product.product_variant_group.product_sku : product.sku,
-
sessions_total: sessions_total,
-
sessions_percentage: calculate_session_percentage(sessions_total, seller_sessions_total),
-
page_views_total: product_views_total(catalogue_id),
-
page_views_percentage_total: calculate_page_views_percentage(catalogue_id),
-
featured_offer_buy_box_per: featured_offer_buy_box_per(product),
-
units_ordered: units_ordered_by_items(order_items),
-
units_ordered_percentage: units_ordered_percentage(order_items, orders),
-
ordered_product_sales: ordered_items_product_sales(order_items),
-
total_order_item: order_items.count
-
}
-
end
-
end
-
-
1
def return_report
-
4
orders.group_by { |order| order.order_placed_at.to_date }.map do |order_placed_at, orders|
-
{
-
2
date: order_placed_at,
-
ordered_product_sales: ordered_product_sales(orders),
-
units_ordered: units_ordered(orders),
-
total_order_item: total_order_items(orders),
-
units_refunded: units_refunded(orders),
-
refund_rate: refund_rate(orders),
-
feedback_received: feedback_received(orders),
-
negative_feedback_received: negative_feedback_received(orders),
-
received_negative_feedback_rate: received_negative_feedback_rate(orders),
-
a_z_claims_granted: a_z_claims_granted(orders),
-
claims_amount: claims_amount(orders)
-
}
-
end
-
end
-
-
1
def compare_sales_report
-
{
-
2
today_so_far: calculate_metrics(Date.today),
-
yesterday: calculate_metrics(Date.yesterday),
-
same_day_last_week: calculate_metrics(Date.today - 7.days),
-
same_day_last_year: calculate_metrics(Date.today - 1.year),
-
percentage_change_from_yesterday: calculate_percentage_change(Date.today, Date.yesterday),
-
percentage_change_from_same_day_last_week: calculate_percentage_change(Date.today, Date.today - 7.days),
-
percentage_change_from_same_day_last_year: calculate_percentage_change(Date.today, Date.today - 1.year)
-
}
-
end
-
-
1
def calculate_metrics(date)
-
20
orders_for_date = orders_for(date)
-
{
-
20
total_order_item: total_order_items(orders_for_date),
-
units_ordered: units_ordered(orders_for_date),
-
ordered_product_sales: ordered_product_sales(orders_for_date),
-
average_units_or_order_item: average_units_per_order_items(orders_for_date),
-
average_sales_or_order_item: average_sales_per_order_items(orders_for_date)
-
}
-
end
-
-
1
def orders_for(date)
-
20
build_order_query(date.beginning_of_day, date.end_of_day)
-
end
-
-
1
def calculate_percentage_change(current_date, comparison_date)
-
6
current_metrics = calculate_metrics(current_date)
-
6
comparison_date = calculate_metrics(comparison_date)
-
-
{
-
6
total_order_item: percentage_change(current_metrics[:total_order_item], comparison_date[:total_order_item]),
-
units_ordered: percentage_change(current_metrics[:units_ordered], comparison_date[:units_ordered]),
-
ordered_product_sales: percentage_change(current_metrics[:ordered_product_sales], comparison_date[:ordered_product_sales]),
-
average_units_or_order_item: percentage_change(current_metrics[:average_units_or_order_item], comparison_date[:average_units_or_order_item]),
-
average_sales_or_order_item: percentage_change(current_metrics[:average_sales_or_order_item], comparison_date[:average_sales_or_order_item])
-
}
-
end
-
-
1
def percentage_change(current_value, previous_value)
-
30
return 0 if previous_value.zero?
-
-
((current_value - previous_value) / previous_value.to_f * 100).round(2)
-
end
-
-
1
def units_refunded(orders)
-
4
if @seller
-
4
order_items = filter_order_items_by_seller(orders.flat_map(&:order_items))
-
8
order_items.select {|order_item| order_item.order_status&.status == 'refunded' }.sum(&:quantity)
-
else
-
orders.sum {|order| order.order_items.select {|order_item| order_item.order_status&.status == 'refunded' }.sum(&:quantity) }
-
end
-
end
-
-
1
def refund_rate(orders)
-
2
units_ordered(orders).zero? ? 0 : (units_refunded(orders).to_f / units_ordered(orders) * 100).round(2)
-
end
-
-
1
def feedback_received(orders)
-
4
catalogue_ids = get_catalogue_ids(orders).uniq
-
4
BxBlockCatalogue::Review.where(review_type: 'product', catalogue_id: catalogue_ids).count
-
end
-
-
1
def negative_feedback_received(orders)
-
2
catalogue_ids = get_catalogue_ids(orders).uniq
-
2
BxBlockCatalogue::Review.where(review_type: 'product', catalogue_id: catalogue_ids).select {|review| review.rating < 3 }.count
-
end
-
-
1
def received_negative_feedback_rate(orders)
-
2
total_feedback = feedback_received(orders)
-
2
total_feedback.zero? ? 0 : (negative_feedback_received(orders).to_f / total_feedback * 100).round(2)
-
end
-
-
1
def a_z_claims_granted(orders)
-
2
if @seller
-
2
order_items = filter_order_items_by_seller(orders.flat_map(&:order_items))
-
4
order_items.select {|order_item| order_item.order_status&.status == 'refunded' }.count
-
else
-
orders.sum {|order| order.order_items.select {|order_item| order_item.order_status&.status == 'refunded' }.count }
-
end
-
end
-
-
1
def claims_amount(orders)
-
2
if @seller
-
2
order_items = filter_order_items_by_seller(orders.flat_map(&:order_items))
-
4
order_items.select {|order_item| order_item.order_status&.status == 'refunded' }.sum(&:price)
-
else
-
orders.sum {|order| order.order_items.select {|order_item| order_item.order_status&.status == 'refunded' }.sum(&:price) }
-
end
-
end
-
-
1
def ordered_product_sales(orders)
-
# total sales revenue
-
51
order_items = filter_order_items_by_seller(orders.flat_map(&:order_items))
-
78
order_items.sum { |order_item| order_item.price * order_item.quantity }.round(2)
-
end
-
-
1
def ordered_items_product_sales(order_items)
-
2
order_items.sum(&:price).round(2)
-
end
-
-
1
def units_ordered(orders)
-
# total items sold including quantity
-
42
order_items = filter_order_items_by_seller(orders.flat_map(&:order_items))
-
42
order_items.sum(&:quantity)
-
end
-
-
1
def units_ordered_by_items(order_items)
-
# total items sold including quantity
-
4
order_items = filter_order_items_by_seller(order_items) if @seller
-
4
order_items.sum(&:quantity)
-
end
-
-
1
def units_ordered_percentage(order_items, orders)
-
2
total_units = units_ordered(orders)
-
2
return 0 if total_units.zero?
-
# units ordered based on order items / all orders unit count
-
2
(units_ordered_by_items(order_items) / total_units.to_f * 100).round(2)
-
end
-
-
1
def total_order_items(orders)
-
# total items sold
-
28
get_catalogue_ids(orders).count
-
end
-
-
1
def average_sales_per_order_items(orders)
-
# average sale per uniq product items
-
# total revenue / total uniq items
-
23
unique_count = get_catalogue_ids(orders).uniq.count
-
23
total_sales = ordered_product_sales(orders)
-
23
return 0 if unique_count.zero?
-
-
11
(total_sales / unique_count).round(2)
-
end
-
-
1
def average_units_per_order_items(orders)
-
# average quantity per uniq product items
-
# total items / uniq product items
-
23
unique_count = get_catalogue_ids(orders).uniq.count
-
23
return 0 if unique_count.zero?
-
-
11
units_ordered(orders) / unique_count
-
end
-
-
1
def featured_offer_buy_box_per(catalogue)
-
# how many items sold by the seller 1 item A and other sellers item A(this is identified by same besku)
-
2
order_ids = BxBlockShoppingCart::Order.where.not(order_placed_at: nil).pluck(:id)
-
2
order_items = BxBlockShoppingCart::OrderItem.includes(:catalogue).where(catalogues: { besku: catalogue.besku }, order_id: order_ids)
-
2
total_besku_products_count = order_items.sum(:quantity)
-
2
return 0 if total_besku_products_count.zero?
-
-
2
seller_besku_products_count = order_items.where(catalogues: { seller_id: catalogue.seller_id }).sum(:quantity)
-
-
2
(seller_besku_products_count.to_f / total_besku_products_count * 100).round(2)
-
end
-
-
1
def get_catalogue_ids(orders)
-
124
catalogue_ids = orders.map {|order| order.catalogue_ids }.flatten
-
80
if @seller
-
124
catalogue_ids = catalogue_ids.select {|cat| @seller.catalogue_ids.include?(cat) }
-
end
-
-
80
catalogue_ids
-
end
-
-
1
def average_selling_price(orders)
-
# average selling price from total revenue
-
# total revenue / total order items
-
3
total_items = total_order_items(orders)
-
3
return 0 if total_items.zero?
-
-
3
(ordered_product_sales(orders) / total_items).round(2)
-
end
-
-
1
def orders
-
10
@orders ||= build_order_query(@start_date.beginning_of_day, @end_date.end_of_day)
-
end
-
-
1
def build_order_query(start_date, end_date)
-
28
query = BxBlockShoppingCart::Order.where(order_placed_at: start_date..end_date).order(order_placed_at: :desc)
-
28
if @seller
-
28
query = query.includes(order_items: { catalogue: [:seller, :product_content] })
-
.where(catalogues: { seller_id: @seller.id })
-
else
-
query = query.includes(order_items: { catalogue: [:seller, :product_content] })
-
end
-
28
query
-
end
-
-
1
def filter_order_items_by_seller(order_items)
-
# filter items by seller
-
108
return order_items unless @seller
-
180
order_items.select { |item| item.catalogue.seller_id == @seller.id }
-
end
-
-
1
def seller_catalogue_sessions
-
5
seller_catalogues = @seller ? @seller.catalogues : []
-
5
calculate_sessions_total(seller_catalogues)
-
end
-
-
1
def calculate_sessions_total(catalogues)
-
10
product_views = ProductView.where(catalogue_id: catalogues.pluck(:id))
-
-
10
session_count = product_views.group_by(&:catalogue_id).map do |catalogue_id, views|
-
20
views.group_by {|view| view.created_at.to_date }.count
-
end.sum
-
10
session_count
-
end
-
-
1
def calculate_session_percentage(sessions_total, all_order_session_total)
-
5
return 0 if all_order_session_total.zero?
-
5
(sessions_total.to_f / all_order_session_total * 100).round(2)
-
end
-
-
1
def product_views_total(catalogue_id)
-
4
ProductView.where(catalogue_id: catalogue_id).count
-
end
-
-
1
def calculate_page_views_percentage(catalogue_id)
-
2
if @seller
-
# total views of seller product
-
2
seller_product_ids = @seller.catalogue_ids
-
2
total_page_views = ProductView.where(catalogue_id: seller_product_ids).count
-
else
-
# total all product views
-
total_page_views = ProductView.count
-
end
-
-
2
product_page_views = product_views_total(catalogue_id)
-
2
return 0 if total_page_views.zero?
-
-
#perticular product view / total product views(seller/all)
-
2
(product_page_views.to_f / total_page_views * 100).round(2)
-
end
-
-
end
-
end
-
1
module BxBlockSms
-
1
class Provider
-
1
TWILIO = :twilio.freeze
-
1
KARIX = :karix.freeze
-
1
TEST = :test.freeze
-
1
UNIFONIC = :unifonic.freeze
-
-
1
SUPPORTED = [TWILIO, KARIX, TEST, UNIFONIC].freeze
-
-
1
class << self
-
1
def send_sms(to, text_content)
-
9
provider_klass = case provider_name
-
when TWILIO
-
Providers::Twilio
-
when KARIX
-
Providers::Karix
-
when UNIFONIC
-
9
Providers::Unifonic
-
when TEST
-
Providers::Test
-
else
-
raise unsupported_message(provider_name)
-
end
-
-
9
provider_klass.send_sms(to, text_content)
-
end
-
-
1
def provider_name
-
9
UNIFONIC
-
end
-
-
1
def unsupported_message(provider)
-
supported_prov_msg = "Supported: #{SUPPORTED.join(", ")}."
-
if provider
-
"Unsupported SMS provider: #{provider}. #{supported_prov_msg}"
-
else
-
"You must specify a SMS provider. #{supported_prov_msg}"
-
end
-
end
-
end
-
end
-
end
-
1
require "uri"
-
1
require "net/http"
-
-
1
module BxBlockSms
-
1
module Providers
-
1
class Unifonic
-
1
class << self
-
1
def send_sms(full_phone_number, text_content)
-
9
send_unifonic_api(full_phone_number, text_content)
-
end
-
-
1
private
-
-
1
def send_unifonic_api(full_phone_number, text_content)
-
9
url = URI.parse('https://el.cloud.unifonic.com/rest/SMS/messages')
-
9
https = Net::HTTP.new(url.host, url.port)
-
9
https.use_ssl = true
-
-
9
request = Net::HTTP::Post.new(url.path)
-
9
request.set_form_data(get_request_data(full_phone_number, text_content))
-
-
9
response = https.request(request)
-
9
puts response.read_body
-
end
-
-
1
def get_request_data(full_phone_number, text_content)
-
{
-
9
"AppSid" => ENV['UNIFONIC_APPSID'],
-
"SenderID" => ENV['UNIFONIC_SENDERID'],
-
"Recipient" => full_phone_number,
-
"Body" => text_content,
-
"async" => true
-
}
-
end
-
-
# def unifonic_message_url
-
# 'https://el.cloud.unifonic.com/rest/SMS/messages'
-
# end
-
-
# def unifonic_source
-
# Rails.configuration.x.sms.from
-
# end
-
end
-
end
-
end
-
end
-
1
module BxBlockSms
-
1
class SendSms
-
1
attr_reader :to, :text_content
-
-
1
def initialize(to, text_content)
-
9
@to = to
-
9
@text_content = text_content
-
end
-
-
1
def call
-
9
Provider.send_sms(to, text_content)
-
end
-
end
-
end
-
1
require_relative 'boot'
-
-
1
require "rails"
-
# Pick the frameworks you want:
-
1
require "active_model/railtie"
-
1
require "active_job/railtie"
-
1
require "active_record/railtie"
-
1
require "active_storage/engine"
-
1
require "action_controller/railtie"
-
1
require "action_mailer/railtie"
-
1
require "action_mailbox/engine"
-
1
require "action_text/engine"
-
1
require "action_view/railtie"
-
1
require "action_cable/engine"
-
# require "sprockets/railtie"
-
# require "rails/test_unit/railtie"
-
-
# Require the gems listed in Gemfile, including any gems
-
# you've limited to :test, :development, or :production.
-
1
Bundler.require(*Rails.groups)
-
-
1
module App
-
1
class Application < Rails::Application
-
# Initialize configuration defaults for originally generated Rails version.
-
1
config.load_defaults 6.0
-
-
1
config.time_zone = ENV['TIME_ZONE']
-
-
1
config.active_record.default_timezone = :local
-
-
# Settings in config/environments/* take precedence over those specified here.
-
# Application configuration can go into files in config/initializers
-
# -- all .rb files in that directory are automatically loaded after loading
-
# the framework and any gems in your application.
-
-
# Only loads a smaller set of middleware suitable for API only apps.
-
# Middleware like session, flash, cookies can be added back manually.
-
# Skip views, helpers and assets when generating a new resource.
-
1
config.api_only = true
-
1
config.middleware.insert_before 0, Rack::Cors do
-
1
allow do
-
1
origins '*'
-
1
resource '*', headers: :any, methods: %i[put patch delete get post options]
-
end
-
end
-
1
config.middleware.use ActionDispatch::Flash
-
1
config.session_store :cookie_store, key: '_interslice_session'
-
1
config.middleware.use ActionDispatch::Cookies
-
1
config.middleware.use ActionDispatch::Session::CookieStore,
-
config.session_options
-
1
config.middleware.use Rack::MethodOverride
-
1
config.middleware.insert_after ActionDispatch::Flash, Warden::Manager
-
end
-
end
-
1
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
-
-
1
require 'bundler/setup' # Set up gems listed in the Gemfile.
-
# Load the Rails application.
-
1
require_relative 'application'
-
-
# Initialize the Rails application.
-
1
Rails.application.initialize!
-
# The test environment is used exclusively to run your application's
-
# test suite. You never need to work with it otherwise. Remember that
-
# your test database is "scratch space" for the test suite and is wiped
-
# and recreated between test runs. Don't rely on the data there!
-
-
1
Rails.application.configure do
-
1
config.hosts = nil
-
# Settings specified here will take precedence over those in config/application.rb.
-
-
1
config.cache_classes = true
-
1
config.log_level = ENV['RAILS_LOGLEVEL'].present? ? ENV['RAILS_LOGLEVEL'].to_sym : :info
-
# Do not eager load code on boot. This avoids loading your whole application
-
# just for the purpose of running a single test. If you are using a tool that
-
# preloads Rails for running tests, you may have to set it to true.
-
1
config.eager_load = false
-
-
# Configure public file server for tests with Cache-Control for performance.
-
1
config.public_file_server.enabled = true
-
1
config.public_file_server.headers = {
-
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
-
}
-
-
# Show full error reports and disable caching.
-
1
config.consider_all_requests_local = true
-
1
config.action_controller.perform_caching = false
-
1
config.cache_store = :null_store
-
-
# Raise exceptions instead of rendering exception templates.
-
1
config.action_dispatch.show_exceptions = false
-
-
# Disable request forgery protection in test environment.
-
1
config.action_controller.allow_forgery_protection = false
-
-
# Store uploaded files on the local file system in a temporary directory.
-
1
config.active_storage.service = :test
-
-
1
config.action_mailer.perform_caching = false
-
-
# Tell Action Mailer not to deliver emails to the real world.
-
# The :test delivery method accumulates sent emails in the
-
# ActionMailer::Base.deliveries array.
-
1
config.action_mailer.delivery_method = :test
-
-
# Print deprecation notices to the stderr.
-
1
config.active_support.deprecation = :stderr
-
1
config.active_job.queue_adapter = :sidekiq
-
-
# Raises error for missing translations.
-
# config.action_view.raise_on_missing_translations = true
-
end
-
1
ActiveAdmin.setup do |config|
-
# == Site Title
-
#
-
# Set the title that is displayed on the main layout
-
# for each of the active admin pages.
-
#
-
1
config.site_title = "ByEzzy"
-
-
# Set the link url for the title. For example, to take
-
# users to your main site. Defaults to no link.
-
#
-
# config.site_title_link = "/"
-
-
# Set an optional image to be displayed for the header
-
# instead of a string (overrides :site_title)
-
#
-
# Note: Aim for an image that's 21px high so it fits in the header.
-
#
-
# config.site_title_image = "logo.png"
-
-
# == Default Namespace
-
#
-
# Set the default namespace each administration resource
-
# will be added to.
-
#
-
# eg:
-
# config.default_namespace = :hello_world
-
#
-
# This will create resources in the HelloWorld module and
-
# will namespace routes to /hello_world/*
-
#
-
# To set no namespace by default, use:
-
# config.default_namespace = false
-
#
-
# Default:
-
# config.default_namespace = :admin
-
#
-
# You can customize the settings for each namespace by using
-
# a namespace block. For example, to change the site title
-
# within a namespace:
-
#
-
# config.namespace :admin do |admin|
-
# admin.site_title = "Custom Admin Title"
-
# end
-
#
-
# This will ONLY change the title for the admin section. Other
-
# namespaces will continue to use the main "site_title" configuration.
-
-
# == User Authentication
-
#
-
# Active Admin will automatically call an authentication
-
# method in a before filter of all controller actions to
-
# ensure that there is a currently logged in admin user.
-
#
-
# This setting changes the method which Active Admin calls
-
# within the application controller.
-
1
config.authentication_method = :authenticate_admin_user!
-
-
# == User Authorization
-
#
-
# Active Admin will automatically call an authorization
-
# method in a before filter of all controller actions to
-
# ensure that there is a user with proper rights. You can use
-
# CanCanAdapter or make your own. Please refer to documentation.
-
# config.authorization_adapter = ActiveAdmin::CanCanAdapter
-
-
# In case you prefer Pundit over other solutions you can here pass
-
# the name of default policy class. This policy will be used in every
-
# case when Pundit is unable to find suitable policy.
-
# config.pundit_default_policy = "MyDefaultPunditPolicy"
-
-
# If you wish to maintain a separate set of Pundit policies for admin
-
# resources, you may set a namespace here that Pundit will search
-
# within when looking for a resource's policy.
-
# config.pundit_policy_namespace = :admin
-
-
# You can customize your CanCan Ability class name here.
-
# config.cancan_ability_class = "Ability"
-
-
# You can specify a method to be called on unauthorized access.
-
# This is necessary in order to prevent a redirect loop which happens
-
# because, by default, user gets redirected to Dashboard. If user
-
# doesn't have access to Dashboard, he'll end up in a redirect loop.
-
# Method provided here should be defined in application_controller.rb.
-
# config.on_unauthorized_access = :access_denied
-
-
# == Current User
-
#
-
# Active Admin will associate actions with the current
-
# user performing them.
-
#
-
# This setting changes the method which Active Admin calls
-
# (within the application controller) to return the currently logged in user.
-
1
config.current_user_method = :current_admin_user
-
-
# == Logging Out
-
#
-
# Active Admin displays a logout link on each screen. These
-
# settings configure the location and method used for the link.
-
#
-
# This setting changes the path where the link points to. If it's
-
# a string, the strings is used as the path. If it's a Symbol, we
-
# will call the method to return the path.
-
#
-
# Default:
-
1
config.logout_link_path = :destroy_admin_user_session_path
-
-
# This setting changes the http method used when rendering the
-
# link. For example :get, :delete, :put, etc..
-
#
-
# Default:
-
# config.logout_link_method = :get
-
-
# == Root
-
#
-
# Set the action to call for the root path. You can set different
-
# roots for each namespace.
-
#
-
# Default:
-
1
config.root_to = 'admin_users#index'
-
-
# == Admin Comments
-
#
-
# This allows your users to comment on any resource registered with Active Admin.
-
#
-
# You can completely disable comments:
-
1
config.comments = false
-
#
-
# You can change the name under which comments are registered:
-
# config.comments_registration_name = 'AdminComment'
-
#
-
# You can change the order for the comments and you can change the column
-
# to be used for ordering:
-
# config.comments_order = 'created_at ASC'
-
#
-
# You can disable the menu item for the comments index page:
-
# config.comments_menu = false
-
#
-
# You can customize the comment menu:
-
# config.comments_menu = { parent: 'Admin', priority: 1 }
-
-
# == Batch Actions
-
#
-
# Enable and disable Batch Actions
-
#
-
1
config.batch_actions = true
-
-
# == Controller Filters
-
#
-
# You can add before, after and around filters to all of your
-
# Active Admin resources and pages from here.
-
#
-
# config.before_action :do_something_awesome
-
-
# == Attribute Filters
-
#
-
# You can exclude possibly sensitive model attributes from being displayed,
-
# added to forms, or exported by default by ActiveAdmin
-
#
-
1
config.filter_attributes = [:encrypted_password, :password, :password_confirmation]
-
-
# == Localize Date/Time Format
-
#
-
# Set the localize format to display dates and times.
-
# To understand how to localize your app with I18n, read more at
-
# https://guides.rubyonrails.org/i18n.html
-
#
-
# You can run `bin/rails runner 'puts I18n.t("date.formats")'` to see the
-
# available formats in your application.
-
#
-
1
config.localize_format = :long
-
-
# == Setting a Favicon
-
#
-
1
config.favicon = 'favicon.png'
-
-
#
-
# Add additional meta tags to the head element of active admin pages.
-
#
-
# Add tags to all pages logged in users see:
-
# config.meta_tags = { author: 'My Company' }
-
-
# By default, sign up/sign in/recover password pages are excluded
-
# from showing up in search engine results by adding a robots meta
-
# tag. You can reset the hash of meta tags included in logged out
-
# pages:
-
# config.meta_tags_for_logged_out_pages = {}
-
-
# == Removing Breadcrumbs
-
#
-
# Breadcrumbs are enabled by default. You can customize them for individual
-
# resources or you can disable them globally from here.
-
#
-
# config.breadcrumb = false
-
-
# == Create Another Checkbox
-
#
-
# Create another checkbox is disabled by default. You can customize it for individual
-
# resources or you can enable them globally from here.
-
#
-
# config.create_another = true
-
-
# == Register Stylesheets & Javascripts
-
#
-
# We recommend using the built in Active Admin layout and loading
-
# up your own stylesheets / javascripts to customize the look
-
# and feel.
-
#
-
# To load a stylesheet:
-
# config.register_stylesheet 'my_stylesheet.css'
-
#
-
# You can provide an options hash for more control, which is passed along to stylesheet_link_tag():
-
# config.register_stylesheet 'my_print_stylesheet.css', media: :print
-
#
-
# To load a javascript file:
-
# config.register_javascript 'my_javascript.js'
-
-
# == CSV options
-
#
-
# Set the CSV builder separator
-
# config.csv_options = { col_sep: ';' }
-
#
-
# Force the use of quotes
-
# config.csv_options = { force_quotes: true }
-
-
# == Menu System
-
#
-
# You can add a navigation menu to be used in your application, or configure a provided menu
-
#
-
# To change the default utility navigation to show a link to your website & a logout btn
-
#
-
# config.namespace :admin do |admin|
-
# admin.build_menu :utility_navigation do |menu|
-
# menu.add label: "My Great Website", url: "http://www.mygreatwebsite.com", html_options: { target: :blank }
-
# admin.add_logout_button_to_menu menu
-
# end
-
# end
-
#
-
# If you wanted to add a static menu item to the default menu provided:
-
#
-
# config.namespace :admin do |admin|
-
# admin.build_menu :default do |menu|
-
# menu.add label: "My Great Website", url: "http://www.mygreatwebsite.com", html_options: { target: :blank }
-
# end
-
# end
-
-
# == Download Links
-
#
-
# You can disable download links on resource listing pages,
-
# or customize the formats shown per namespace/globally
-
#
-
# To disable/customize for the :admin namespace:
-
#
-
# config.namespace :admin do |admin|
-
#
-
# # Disable the links entirely
-
# admin.download_links = false
-
#
-
# # Only show XML & PDF options
-
# admin.download_links = [:xml, :pdf]
-
#
-
# # Enable/disable the links based on block
-
# # (for example, with cancan)
-
# admin.download_links = proc { can?(:view_download_links) }
-
#
-
# end
-
-
# == Pagination
-
#
-
# Pagination is enabled by default for all resources.
-
# You can control the default per page count for all resources here.
-
#
-
# config.default_per_page = 30
-
#
-
# You can control the max per page count too.
-
#
-
# config.max_per_page = 10_000
-
-
# == Filters
-
#
-
# By default the index screen includes a "Filters" sidebar on the right
-
# hand side with a filter for each attribute of the registered model.
-
# You can enable or disable them for all resources here.
-
#
-
# config.filters = true
-
#
-
# By default the filters include associations in a select, which means
-
# that every record will be loaded for each association (up
-
# to the value of config.maximum_association_filter_arity).
-
# You can enabled or disable the inclusion
-
# of those filters by default here.
-
#
-
# config.include_default_association_filters = true
-
-
# config.maximum_association_filter_arity = 256 # default value of :unlimited will change to 256 in a future version
-
# config.filter_columns_for_large_association = [
-
# :display_name,
-
# :full_name,
-
# :name,
-
# :username,
-
# :login,
-
# :title,
-
# :email,
-
# ]
-
# config.filter_method_for_large_association = '_starts_with'
-
-
# == Head
-
#
-
# You can add your own content to the site head like analytics. Make sure
-
# you only pass content you trust.
-
#
-
# config.head = ''.html_safe
-
-
# == Footer
-
#
-
# By default, the footer shows the current Active Admin version. You can
-
# override the content of the footer here.
-
#
-
# config.footer = 'my custom footer text'
-
-
# == Sorting
-
#
-
# By default ActiveAdmin::OrderClause is used for sorting logic
-
# You can inherit it with own class and inject it for all resources
-
#
-
# config.order_clause = MyOrderClause
-
-
# == Webpacker
-
#
-
# By default, Active Admin uses Sprocket's asset pipeline.
-
# You can switch to using Webpacker here.
-
#
-
# config.use_webpacker = true
-
-
1
config.register_stylesheet 'active_admin/json_editor.css'
-
1
config.register_javascript 'active_admin/json_editor.js'
-
1
config.register_javascript "//cdn.ckeditor.com/4.22.1/full-all/ckeditor.js"
-
end
-
# Be sure to restart your server when you modify this file.
-
-
# ActiveSupport::Reloader.to_prepare do
-
# ApplicationController.renderer.defaults.merge!(
-
# http_host: 'example.org',
-
# https: false
-
# )
-
# end
-
# Be sure to restart your server when you modify this file.
-
-
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
-
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
-
-
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
-
# Rails.backtrace_cleaner.remove_silencers!
-
# frozen_string_literal: true
-
-
# Use this hook to configure ckeditor
-
1
Ckeditor.setup do |config|
-
# ==> ORM configuration
-
# Load and configure the ORM. Supports :active_record (default), :mongo_mapper and
-
# :mongoid (bson_ext recommended) by default. Other ORMs may be
-
# available as additional gems.
-
1
require 'ckeditor/orm/active_record'
-
-
# Allowed image file types for upload.
-
# Set to nil or [] (empty array) for all file types
-
# By default: %w(jpg jpeg png gif tiff)
-
# config.image_file_types = %w(jpg jpeg png gif tiff)
-
-
# Allowed flash file types for upload.
-
# Set to nil or [] (empty array) for all file types
-
# By default: %w(jpg jpeg png gif tiff)
-
# config.flash_file_types = %w(swf)
-
-
# Allowed attachment file types for upload.
-
# Set to nil or [] (empty array) for all file types
-
# By default: %w(doc docx xls odt ods pdf rar zip tar tar.gz swf)
-
# config.attachment_file_types = %w(doc docx xls odt ods pdf rar zip tar tar.gz swf)
-
-
# Setup authorization to be run as a before filter
-
# By default: there is no authorization.
-
# config.authorize_with :cancancan
-
-
# Override parent controller CKEditor inherits from
-
# By default: 'ApplicationController'
-
# config.parent_controller = 'MyController'
-
-
# Asset model classes
-
# config.picture_model { Ckeditor::Picture }
-
# config.attachment_file_model { Ckeditor::AttachmentFile }
-
-
# Paginate assets
-
# By default: 24
-
# config.default_per_page = 24
-
-
# Customize ckeditor assets path
-
# By default: nil
-
# config.asset_path = 'http://www.example.com/assets/ckeditor/'
-
-
# CKEditor CDN
-
# More info here http://cdn.ckeditor.com/
-
# By default: nil (CDN disabled)
-
# config.cdn_url = '//cdn.ckeditor.com/4.22.1/standard/ckeditor.js'
-
-
# JS config url
-
# Used when CKEditor CDN enabled
-
# By default: "ckeditor/config.js"
-
# config.js_config_url = 'ckeditor/config.js'
-
end
-
# Be sure to restart your server when you modify this file.
-
-
# Avoid CORS issues when API is called from the frontend app.
-
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
-
-
# Read more: https://github.com/cyu/rack-cors
-
-
1
Rails.application.config.middleware.insert_before 0, Rack::Cors do
-
1
allow do
-
1
origins '*'
-
1
resource '*', headers: :any, methods: [:get, :post, :patch, :put, :delete, :options, :head]
-
end
-
end
-
# frozen_string_literal: true
-
-
# Assuming you have not yet modified this file, each configuration option below
-
# is set to its default value. Note that some are commented out while others
-
# are not: uncommented lines are intended to protect your configuration from
-
# breaking changes in upgrades (i.e., in the event that future versions of
-
# Devise change the default values for those options).
-
#
-
# Use this hook to configure devise mailer, warden hooks and so forth.
-
# Many of these configuration options can be set straight in your model.
-
1
Devise.setup do |config|
-
# The secret key used by Devise. Devise uses this key to generate
-
# random tokens. Changing this key will render invalid all existing
-
# confirmation, reset password and unlock tokens in the database.
-
# Devise will use the `secret_key_base` as its `secret_key`
-
# by default. You can change it below and use your own secret key.
-
# config.secret_key = '2e2970710f01f9699af20a0a176726b25f01098178703e57f09a1ec9b356e4caf6623febd42c8d94072c979388e528b46662defa3232670ee5fd0ce94d660c97'
-
-
# ==> Controller configuration
-
# Configure the parent class to the devise controllers.
-
# config.parent_controller = 'DeviseController'
-
-
# ==> Mailer Configuration
-
# Configure the e-mail address which will be shown in Devise::Mailer,
-
# note that it will be overwritten if you use your own mailer class
-
# with default "from" parameter.
-
1
config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
-
-
# Configure the class responsible to send e-mails.
-
# config.mailer = 'Devise::Mailer'
-
-
# Configure the parent class responsible to send e-mails.
-
# config.parent_mailer = 'ActionMailer::Base'
-
-
# ==> ORM configuration
-
# Load and configure the ORM. Supports :active_record (default) and
-
# :mongoid (bson_ext recommended) by default. Other ORMs may be
-
# available as additional gems.
-
1
require 'devise/orm/active_record'
-
-
# ==> Configuration for any authentication mechanism
-
# Configure which keys are used when authenticating a user. The default is
-
# just :email. You can configure it to use [:username, :subdomain], so for
-
# authenticating a user, both parameters are required. Remember that those
-
# parameters are used only when authenticating and not when retrieving from
-
# session. If you need permissions, you should implement that in a before filter.
-
# You can also supply a hash where the value is a boolean determining whether
-
# or not authentication should be aborted when the value is not present.
-
# config.authentication_keys = [:email]
-
-
# Configure parameters from the request object used for authentication. Each entry
-
# given should be a request method and it will automatically be passed to the
-
# find_for_authentication method and considered in your model lookup. For instance,
-
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
-
# The same considerations mentioned for authentication_keys also apply to request_keys.
-
# config.request_keys = []
-
-
# Configure which authentication keys should be case-insensitive.
-
# These keys will be downcased upon creating or modifying a user and when used
-
# to authenticate or find a user. Default is :email.
-
1
config.case_insensitive_keys = [:email]
-
-
# Configure which authentication keys should have whitespace stripped.
-
# These keys will have whitespace before and after removed upon creating or
-
# modifying a user and when used to authenticate or find a user. Default is :email.
-
1
config.strip_whitespace_keys = [:email]
-
-
# Tell if authentication through request.params is enabled. True by default.
-
# It can be set to an array that will enable params authentication only for the
-
# given strategies, for example, `config.params_authenticatable = [:database]` will
-
# enable it only for database (email + password) authentication.
-
# config.params_authenticatable = true
-
-
# Tell if authentication through HTTP Auth is enabled. False by default.
-
# It can be set to an array that will enable http authentication only for the
-
# given strategies, for example, `config.http_authenticatable = [:database]` will
-
# enable it only for database authentication.
-
# For API-only applications to support authentication "out-of-the-box", you will likely want to
-
# enable this with :database unless you are using a custom strategy.
-
# The supported strategies are:
-
# :database = Support basic authentication with authentication key + password
-
# config.http_authenticatable = false
-
-
# If 401 status code should be returned for AJAX requests. True by default.
-
# config.http_authenticatable_on_xhr = true
-
-
# The realm used in Http Basic Authentication. 'Application' by default.
-
# config.http_authentication_realm = 'Application'
-
-
# It will change confirmation, password recovery and other workflows
-
# to behave the same regardless if the e-mail provided was right or wrong.
-
# Does not affect registerable.
-
# config.paranoid = true
-
-
# By default Devise will store the user in session. You can skip storage for
-
# particular strategies by setting this option.
-
# Notice that if you are skipping storage for all authentication paths, you
-
# may want to disable generating routes to Devise's sessions controller by
-
# passing skip: :sessions to `devise_for` in your config/routes.rb
-
1
config.skip_session_storage = [:http_auth]
-
-
# By default, Devise cleans up the CSRF token on authentication to
-
# avoid CSRF token fixation attacks. This means that, when using AJAX
-
# requests for sign in and sign up, you need to get a new CSRF token
-
# from the server. You can disable this option at your own risk.
-
# config.clean_up_csrf_token_on_authentication = true
-
-
# When false, Devise will not attempt to reload routes on eager load.
-
# This can reduce the time taken to boot the app but if your application
-
# requires the Devise mappings to be loaded during boot time the application
-
# won't boot properly.
-
# config.reload_routes = true
-
-
# ==> Configuration for :database_authenticatable
-
# For bcrypt, this is the cost for hashing the password and defaults to 12. If
-
# using other algorithms, it sets how many times you want the password to be hashed.
-
# The number of stretches used for generating the hashed password are stored
-
# with the hashed password. This allows you to change the stretches without
-
# invalidating existing passwords.
-
#
-
# Limiting the stretches to just one in testing will increase the performance of
-
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
-
# a value less than 10 in other environments. Note that, for bcrypt (the default
-
# algorithm), the cost increases exponentially with the number of stretches (e.g.
-
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
-
1
config.stretches = Rails.env.test? ? 1 : 12
-
-
# Set up a pepper to generate the hashed password.
-
# config.pepper = '1133c02f932c0b6d3ed3f99d38cbdc09af3e59c5d8dd9c3873b98cc80e6e41646c32f71d8f3767a53795ceb8f3c3be144d6470ba61e9c4d5076ef7bce99b8f9f'
-
-
# Send a notification to the original email when the user's email is changed.
-
# config.send_email_changed_notification = false
-
-
# Send a notification email when the user's password is changed.
-
# config.send_password_change_notification = false
-
-
# ==> Configuration for :confirmable
-
# A period that the user is allowed to access the website even without
-
# confirming their account. For instance, if set to 2.days, the user will be
-
# able to access the website for two days without confirming their account,
-
# access will be blocked just in the third day.
-
# You can also set it to nil, which will allow the user to access the website
-
# without confirming their account.
-
# Default is 0.days, meaning the user cannot access the website without
-
# confirming their account.
-
# config.allow_unconfirmed_access_for = 2.days
-
-
# A period that the user is allowed to confirm their account before their
-
# token becomes invalid. For example, if set to 3.days, the user can confirm
-
# their account within 3 days after the mail was sent, but on the fourth day
-
# their account can't be confirmed with the token any more.
-
# Default is nil, meaning there is no restriction on how long a user can take
-
# before confirming their account.
-
# config.confirm_within = 3.days
-
-
# If true, requires any email changes to be confirmed (exactly the same way as
-
# initial account confirmation) to be applied. Requires additional unconfirmed_email
-
# db field (see migrations). Until confirmed, new email is stored in
-
# unconfirmed_email column, and copied to email column on successful confirmation.
-
1
config.reconfirmable = true
-
-
# Defines which key will be used when confirming an account
-
# config.confirmation_keys = [:email]
-
-
# ==> Configuration for :rememberable
-
# The time the user will be remembered without asking for credentials again.
-
# config.remember_for = 2.weeks
-
-
# Invalidates all the remember me tokens when the user signs out.
-
1
config.expire_all_remember_me_on_sign_out = true
-
-
# If true, extends the user's remember period when remembered via cookie.
-
# config.extend_remember_period = false
-
-
# Options to be passed to the created cookie. For instance, you can set
-
# secure: true in order to force SSL only cookies.
-
# config.rememberable_options = {}
-
-
# ==> Configuration for :validatable
-
# Range for password length.
-
1
config.password_length = 6..128
-
-
# Email regex used to validate email formats. It simply asserts that
-
# one (and only one) @ exists in the given string. This is mainly
-
# to give user feedback and not to assert the e-mail validity.
-
1
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
-
-
# ==> Configuration for :timeoutable
-
# The time you want to timeout the user session without activity. After this
-
# time the user will be asked for credentials again. Default is 30 minutes.
-
# config.timeout_in = 30.minutes
-
-
# ==> Configuration for :lockable
-
# Defines which strategy will be used to lock an account.
-
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
-
# :none = No lock strategy. You should handle locking by yourself.
-
# config.lock_strategy = :failed_attempts
-
-
# Defines which key will be used when locking and unlocking an account
-
# config.unlock_keys = [:email]
-
-
# Defines which strategy will be used to unlock an account.
-
# :email = Sends an unlock link to the user email
-
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
-
# :both = Enables both strategies
-
# :none = No unlock strategy. You should handle unlocking by yourself.
-
# config.unlock_strategy = :both
-
-
# Number of authentication tries before locking an account if lock_strategy
-
# is failed attempts.
-
# config.maximum_attempts = 20
-
-
# Time interval to unlock the account if :time is enabled as unlock_strategy.
-
# config.unlock_in = 1.hour
-
-
# Warn on the last attempt before the account is locked.
-
# config.last_attempt_warning = true
-
-
# ==> Configuration for :recoverable
-
#
-
# Defines which key will be used when recovering the password for an account
-
# config.reset_password_keys = [:email]
-
-
# Time interval you can reset your password with a reset password key.
-
# Don't put a too small interval or your users won't have the time to
-
# change their passwords.
-
1
config.reset_password_within = 6.hours
-
-
# When set to false, does not sign a user in automatically after their password is
-
# reset. Defaults to true, so a user is signed in automatically after a reset.
-
# config.sign_in_after_reset_password = true
-
-
# ==> Configuration for :encryptable
-
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
-
# You can use :sha1, :sha512 or algorithms from others authentication tools as
-
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
-
# for default behavior) and :restful_authentication_sha1 (then you should set
-
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
-
#
-
# Require the `devise-encryptable` gem when using anything other than bcrypt
-
# config.encryptor = :sha512
-
-
# ==> Scopes configuration
-
# Turn scoped views on. Before rendering "sessions/new", it will first check for
-
# "users/sessions/new". It's turned off by default because it's slower if you
-
# are using only default views.
-
# config.scoped_views = false
-
-
# Configure the default scope given to Warden. By default it's the first
-
# devise role declared in your routes (usually :user).
-
# config.default_scope = :user
-
-
# Set this configuration to false if you want /users/sign_out to sign out
-
# only the current scope. By default, Devise signs out all scopes.
-
# config.sign_out_all_scopes = true
-
-
# ==> Navigation configuration
-
# Lists the formats that should be treated as navigational. Formats like
-
# :html, should redirect to the sign in page when the user does not have
-
# access, but formats like :xml or :json, should return 401.
-
#
-
# If you have any extra navigational formats, like :iphone or :mobile, you
-
# should add them to the navigational formats lists.
-
#
-
# The "*/*" below is required to match Internet Explorer requests.
-
# config.navigational_formats = ['*/*', :html]
-
-
# The default HTTP method used to sign out a resource. Default is :delete.
-
1
config.sign_out_via = :delete
-
-
# ==> OmniAuth
-
# Add a new OmniAuth provider. Check the wiki for more information on setting
-
# up on your models and hooks.
-
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
-
-
# ==> Warden configuration
-
# If you want to use other strategies, that are not supported by Devise, or
-
# change the failure app, you can configure them inside the config.warden block.
-
#
-
# config.warden do |manager|
-
# manager.intercept_401 = false
-
# manager.default_strategies(scope: :user).unshift :some_external_strategy
-
# end
-
-
# ==> Mountable engine configurations
-
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
-
# is mountable, there are some extra configurations to be taken into account.
-
# The following options are available, assuming the engine is mounted as:
-
#
-
# mount MyEngine, at: '/my_engine'
-
#
-
# The router that invoked `devise_for`, in the example above, would be:
-
# config.router_name = :my_engine
-
#
-
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
-
# so you need to do it manually. For the users scope, it would be:
-
# config.omniauth_path_prefix = '/my_engine/users/auth'
-
-
# ==> Turbolinks configuration
-
# If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
-
#
-
# ActiveSupport.on_load(:devise_failure_app) do
-
# include Turbolinks::Controller
-
# end
-
-
# ==> Configuration for :registerable
-
-
# When set to false, does not sign a user in automatically after their password is
-
# changed. Defaults to true, so a user is signed in automatically after changing a password.
-
# config.sign_in_after_change_password = true
-
end
-
# Be sure to restart your server when you modify this file.
-
-
# Configure sensitive parameters which will be filtered from the log file.
-
1
Rails.application.config.filter_parameters += [:password]
-
# Be sure to restart your server when you modify this file.
-
-
# Add new inflection rules using the following format. Inflections
-
# are locale specific, and you may define rules for as many different
-
# locales as you wish. All of these examples are active by default:
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.plural /^(ox)$/i, '\1en'
-
# inflect.singular /^(ox)en/i, '\1'
-
# inflect.irregular 'person', 'people'
-
# inflect.uncountable %w( fish sheep )
-
# end
-
-
# These inflection rules are supported but not enabled by default:
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.acronym 'RESTful'
-
# end
-
# Be sure to restart your server when you modify this file.
-
-
# Add new mime types for use in respond_to blocks:
-
# Mime::Type.register "text/richtext", :rtf
-
-
# if Rails.env.test?
-
# require 'mock_redis'
-
# $redis_onlines = MockRedis.new
-
# end
-
-
1
unless Rails.env.test?
-
REDIS = Redis::Namespace.new(:my_namespace, redis: Redis.new(host: ENV['REDIS_URL'], port: 6379, db: 0) )
-
else
-
1
REDIS = Redis::Namespace.new(:my_namespace, redis: MockRedis.new )
-
end
-
1
require "stripe"
-
1
Rails.configuration.stripe = {
-
publishable_key: ENV["STRIPE_PUB_KEY"],
-
secret_key: ENV["STRIPE_SECRET_KEY"]
-
}
-
-
1
Stripe.api_key = Rails.configuration.stripe[:secret_key]
-
# Be sure to restart your server when you modify this file.
-
-
# This file contains settings for ActionController::ParamsWrapper which
-
# is enabled by default.
-
-
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
-
1
ActiveSupport.on_load(:action_controller) do
-
1
wrap_parameters format: [:json]
-
end
-
-
# To enable root element in JSON for ActiveRecord objects.
-
# ActiveSupport.on_load(:active_record) do
-
# self.include_root_in_json = true
-
# end
-
1
Rails.application.routes.draw do
-
1
get "/healthcheck", to: proc { [200, {}, ["Ok"]] }
-
1
devise_for :admin_users, ActiveAdmin::Devise.config.merge(path: '', path_names: { sign_in: '' })
-
1
ActiveAdmin.routes(self)
-
1
root to: 'active_admin/devise/sessions#new'
-
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
-
-
1
namespace :bx_block_seo_setting do
-
1
resources :seo_settings
-
end
-
-
1
namespace :account_block do
-
1
resources :suggestion_feedbacks
-
1
resources :accounts, only: [:create,:update,:destroy,:show] do
-
1
resources :seller_documents, except: [:destroy]
-
1
post :document_verification_email, to: 'seller_documents#document_verification_email', on: :collection
-
1
post 'resend_email', to: 'accounts#resend_email', on: :collection
-
1
post 'upload_image', to: 'accounts#upload_image', on: :collection
-
1
post 'send_otps', to: 'accounts/send_otps#create', on: :collection
-
1
post 'sms_otp_confirmations', to: 'accounts/sms_confirmations#create', on: :collection
-
1
get 'logged_user', to: 'accounts#logged_user', on: :collection
-
1
resources :user_delivery_addresses, only: [:index,:create,:update,:destroy,:show]
-
end
-
end
-
-
1
get 'account_activation', to: 'account_block/accounts#account_activation'
-
1
post 'send_login_otp', to: 'bx_block_login/logins#send_login_otp'
-
-
1
post '/forgot_password', to: 'bx_block_forgot_password/passwords#forgot_password'
-
1
patch '/reset_password', to: 'bx_block_forgot_password/passwords#reset_password'
-
1
post '/current_password', to: 'bx_block_forgot_password/passwords#current_password'
-
-
1
namespace :bx_block_login do
-
1
resources :logins, only: [:create]
-
end
-
-
1
namespace :bx_block_categories do
-
1
get 'list_sub_categories_from_catalogues', to: 'sub_categories#list_sub_categories_from_catalogues'
-
1
get 'list_subcategories_by_category_ids', to: 'sub_categories#list_subcategories_by_category_ids'
-
1
get 'list_minicategories_by_subcategory_ids', to: 'mini_categories#list_minicategories_by_subcategory_ids'
-
1
get 'list_microcategories_by_minicategory_ids', to: 'micro_categories#list_microcategories_by_minicategory_ids'
-
1
resources :categories, only: [:show,:index] do
-
1
get 'search_micro_categories',to: 'categories#search_micro_categories', on: :collection
-
1
resources :sub_categories, only: [:show,:index] do
-
1
resources :mini_categories, only: [:show,:index] do
-
1
resources :micro_categories, only: [:show,:index]
-
end
-
end
-
1
resources :custom_fields, only: [:show,:index] do
-
1
get 'show_custom_fields', to: 'custom_fields#show_custom_fields', on: :collection
-
end
-
end
-
end
-
-
# get 'search_sub_category', to: 'bx_block_categories/sub_categories#search_sub_category'
-
1
get 'search_brands', to: 'bx_block_catalogue/brands#search_brands'
-
1
get 'search_catalogues', to: 'bx_block_catalogue/catalogues#search_catalogues'
-
-
1
get 'template_download', to: 'bx_block_catalogue/catalogues#template_download'
-
-
1
post 'bulk_upload', to: 'bx_block_catalogue/catalogues#bulk_upload'
-
-
-
1
namespace :bx_block_catalogue do
-
-
1
resources :brands, only: [:create,:index,:show] do
-
1
get 'list_sub_categories_from_brand', on: :collection
-
1
get 'seller_brand_listing', on: :collection
-
1
put 'update_seller_brands', on: :collection
-
1
post 'create_seller_brand', on: :collection
-
1
delete 'delete_seller_brand', on: :collection
-
1
get 'list_brands_from_catalogues', to: 'brands#list_brands_from_catalogues', on: :collection
-
1
get 'approved_brands_index', to: 'brands#approved_brands_index', on: :collection
-
1
get 'restricted_brands_index', to: 'brands#restricted_brands_index', on: :collection
-
1
get 'gated_brands_index', to: 'brands#gated_brands_index', on: :collection
-
1
resources :restricted_brands, only: [:create,:index,:show,:update,:destroy]
-
1
resources :gated_brands, only: [:create,:index,:show]
-
end
-
1
resources :warehouses, only: [:create,:index,:show] do
-
1
post 'create_seller_warehouse', on: :collection
-
1
put 'update_seller_warehouse', on: :collection
-
1
delete 'delete_seller_warehouse', on: :collection
-
1
get 'seller_warehouse_listing', on: :collection
-
1
resources :warehouse_catalogues, only: [:index, :show, :create, :update, :destroy]
-
end
-
1
resources :catalogues, only: [:create,:index,:show,:update] do
-
1
get 'list_store_menu_products', on: :collection
-
1
get 'sku_validate', to: 'catalogues#sku_validate', on: :collection
-
1
post 'list_catalogue_by_category', to: 'catalogues#list_catalogue_by_category', on: :collection
-
1
get 'search_catalogues_by_title_or_brand_name', to: 'catalogues#search_catalogues_by_title_or_brand_name', on: :collection
-
1
get 'search_catalogues_by_brand', to: 'catalogues#search_catalogues_by_brand', on: :collection
-
1
resources :product_contents, only: [:index, :create, :update]
-
1
resources :product_variant_groups, only: [:index, :create, :update, :show, :destroy]
-
1
resources :catalogue_contents, only: [:index, :create, :destroy] do
-
1
patch 'update_catalogue_contents', to: 'catalogue_contents#update_catalogue_contents', on: :collection
-
1
delete 'delete_catalogue_contents', to: 'catalogue_contents#delete_catalogue_contents', on: :collection
-
end
-
1
resources :barcodes, only: [:create,:show,:index, :update]
-
1
resources :catalogue_offers, only: [:create,:show,:update]
-
end
-
-
1
get 'fetch_custom_field_filters', to: 'catalogue_contents#fetch_custom_field_filters'
-
-
1
resources :catalogue_variants, only: [:index, :create, :update, :show, :destroy]
-
-
1
resources :store_fronts, only: [:index] do
-
1
get 'latest_product', on: :collection
-
1
get 'popular_product', on: :collection
-
1
get 'average_rating_for_seller', on: :collection
-
1
get 'average_rating_for_product', on: :collection
-
1
get 'ratings_percentage', on: :collection
-
1
get 'latest_review_for_seller', on: :collection
-
1
get 'list_reviews', on: :collection
-
1
get 'ratings_percentage_for_product', on: :collection
-
1
get 'latest_review_for_product', on: :collection
-
end
-
-
1
resources :deals, only: [:index,:show] do
-
1
resources :deal_catalogues
-
end
-
-
1
resources :reviews do
-
1
get :user_review_listing, on: :collection
-
1
get :seller_happiness_indicator,on: :collection
-
1
get :buyer_review_listing, on: :collection
-
1
get :customer_rating_and_reviews, on: :collection
-
1
resource :helpful_review, only: [:create, :destroy]
-
end
-
-
1
resources :parent_catalogues, only: [] do
-
1
get 'search_parent_catalogues_by_title_or_brand_name', to: 'parent_catalogues#search_parent_catalogues_by_title_or_brand_name', on: :collection
-
end
-
end
-
-
1
namespace :bx_block_termsandconditions do
-
1
resources :terms_policies, only: [:show,:index]
-
1
resources :seller_static_pages, only: [:show, :index] do
-
1
delete 'delete_static_pages', to: '/seller_static_pages/delete_static_pages', on: :collection
-
end
-
1
resources :privacy_and_legal_policy, only: [:show, :index]
-
end
-
-
1
namespace :bx_block_support do
-
1
resources :support_documents, only: [:show,:index] do
-
1
delete 'delete_support_documents', to: '/support_documents/delete_support_documents', on: :collection
-
end
-
1
resources :supports, only: [:create]
-
1
resources :static_pages, only: [:show,:index] do
-
1
delete 'delete_static_pages', to: '/static_pages/delete_static_pages', on: :collection
-
end
-
1
resources :social_platforms, only: [:show,:index]
-
end
-
-
1
namespace :bx_block_store_management do
-
1
resources :stores, only: [:index, :show, :create, :update, :destroy] do
-
1
get "seller_store_listing", on: :collection
-
1
put 'update_seller_store', on: :member
-
1
post 'create_seller_store', on: :collection
-
1
delete 'delete_seller_store', on: :member
-
1
get 'index_approved_stores', to: 'stores#index_approved_stores', on: :collection
-
1
resources :store_menus, only: [:index, :show, :create, :update, :destroy] do
-
1
get 'store_menus_list', to: 'store_menus#store_menus_list', on: :collection
-
end
-
1
resources :store_dashboard_sections, only: [:index, :show, :create, :update, :destroy] do
-
1
resources :store_section_grids, only: [:index, :show, :create, :update, :destroy]
-
end
-
end
-
end
-
-
1
namespace :bx_block_dashboard do
-
1
resources :most_popular_categories, only: [:index, :show]
-
1
resources :header_categories, only: [:index, :show]
-
1
resources :top_brands, only: [:index, :show]
-
1
resources :trending_products, only: [:index, :show] do
-
1
post :list_trending_products, on: :collection
-
end
-
1
resources :weekly_homiee_deals, only: [:index, :show] do
-
1
get 'latest_weekly_deal', on: :collection
-
end
-
1
resources :author_favorite_books, only: [:index, :show] do
-
1
get 'latest_author_favorite', on: :collection
-
end
-
1
resources :banners, only: [] do
-
1
collection do
-
1
get 'header_slideshow', to: 'banners#header_slideshow_index'
-
1
get 'header_single_images', to: 'banners#header_single_images_index'
-
1
get 'middle_slideshow', to: 'banners#middle_slideshow_index'
-
1
get 'middle_single_images', to: 'banners#middle_single_images_index'
-
1
get 'footer_single_images', to: 'banners#footer_single_images_index'
-
1
get 'top_banner', to: 'banners#top_banner'
-
end
-
end
-
-
1
resources :global_searches, only: [] do
-
1
collection do
-
1
post :search
-
1
get :brands_filter_lists
-
1
get :categories_filter_lists
-
end
-
end
-
end
-
-
1
namespace :bx_block_custom_ads do
-
1
resources :advertisements, only: [:index,:show]
-
end
-
-
1
namespace :bx_block_favourites do
-
1
resources :favourites, only: [:index, :create, :destroy]
-
end
-
-
1
namespace :bx_block_shopping_cart do
-
1
resources :return_exchange_requests
-
1
resources :order_items, only: [:create, :destroy, :update, :index] do
-
1
post :guest_user_order, on: :collection
-
end
-
1
resources :return_reason_details
-
1
resources :orders, only: [:index, :show, :update, :destroy] do
-
1
resources :shipped_order_details, only: [:create, :show, :update, :destroy]
-
1
get :show_seller_order, on: :member
-
1
post :apply_coupon_to_order, on: :member
-
1
get :seller_orders, on: :collection
-
1
delete 'destroy_all_orders', on: :collection
-
end
-
1
resources :telr_payments, only: [:create] do
-
1
post :payment_failed_notification, on: :collection
-
1
get :show_or_check, on: :collection
-
end
-
end
-
1
namespace :bx_block_coupon_cg do
-
1
resources :coupon_codes, only: [:index, :show]
-
1
resources :subscribe_coupons, only: [:create, :update, :destroy, :index]
-
end
-
1
namespace :bx_block_order_management do
-
1
resources :order_statues, only: [:index, :show]
-
1
resources :delivery_requests, only: [:create, :update, :destroy, :index, :show]
-
1
resources :stock_intakes, only: [:create, :update, :destroy, :index, :show]
-
1
resources :anchanto_wms do
-
1
match :event_grn_status_update_in_wms, on: :collection, via: [:get, :post]
-
1
post :create_wms_product, on: :collection
-
1
post :create_consignment_order, on: :collection
-
# post :create_b2c_order, on: :collection
-
# post :event_consignment_status_update_in_wms, on: :collection
-
# post :event_b2c_shipment_status_update_in_wms, on: :collection
-
1
match :create_b2c_order, to: :create_b2c_order, via: [:get, :post], on: :collection
-
1
match :event_consignment_status_update_in_wms, to: :event_consignment_status_update_in_wms, via: [:get, :post], on: :collection
-
1
match :event_b2c_shipment_status_update_in_wms, to: :event_b2c_shipment_status_update_in_wms, via: [:get, :post], on: :collection
-
1
post :b2c_order_index, on: :collection
-
1
post :b2c_order_show, on: :collection
-
end
-
end
-
1
namespace :bx_block_contact_us do
-
1
resources :contacts, only: [:create]
-
end
-
-
1
namespace :bx_block_invoicebilling do
-
1
resources :invoice_billings, only: [] do
-
1
collection do
-
1
get :invoice_pdf
-
end
-
end
-
end
-
-
1
namespace :bx_block_salesreporting do
-
1
resources :product_views, only: [:create] do
-
1
get 'browsing_history', on: :collection
-
end
-
1
resources :reports do
-
1
post 'sales_performance', on: :collection
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ActivityLogsController, type: :controller do
-
1
render_views
-
-
-
1
before do
-
2
@admin = FactoryBot.create(:admin_user)
-
2
@account = FactoryBot.create(:account, user_type: "seller")
-
2
@activity = FactoryBot.create(:activity_log, user: @account)
-
2
sign_in @admin
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: @activity.id }
-
1
expect(response).to render_template(:show)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::AdminRepliesController, type: :controller do
-
1
render_views
-
1
before do
-
5
@admin = FactoryBot.create(:admin_user)
-
5
sign_in @admin
-
5
@admin_replies = create_list(:admin_reply, 2)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
@admin_replies.each do |admin_reply|
-
2
expect(response.body).to include(admin_reply.description)
-
2
if admin_reply.image.attached?
-
2
image_url = Rails.application.routes.url_helpers.rails_blob_path(admin_reply.image, only_path: true)
-
2
expect(response.body).to include(image_url)
-
end
-
end
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
admin_reply = @admin_replies.first
-
1
get :show, params: { id: admin_reply.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(admin_reply.description)
-
1
if admin_reply.image.attached?
-
1
image_url = Rails.application.routes.url_helpers.rails_blob_path(admin_reply.image, only_path: true)
-
1
expect(response.body).to include(image_url)
-
end
-
end
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
it 'creates a new admin reply and sends notification' do
-
1
post :create, params: { admin_reply: attributes_for(:admin_reply) }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe '#send_notification' do
-
1
it 'sends a notification email' do
-
1
@admin_replies.each do |admin_reply|
-
2
expect {
-
2
controller.send(:send_notification, admin_reply)
-
4
}.to change { ActionMailer::Base.deliveries.count }.by(1)
-
2
last_email = ActionMailer::Base.deliveries.last
-
2
expect(last_email.to).to include(admin_reply.contact.email)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::AdminUsersController, type: :controller do
-
1
render_views
-
-
1
before do
-
4
@admin = FactoryBot.create(:admin_user)
-
4
sign_in @admin
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by email' do
-
1
get :index, params: { q: { email_cont: @admin.email } }
-
1
expect(response).to render_template(:index)
-
end
-
-
1
it 'filters by created_at' do
-
1
user1 = FactoryBot.create(:admin_user, created_at: 1.day.ago)
-
1
user2 = FactoryBot.create(:admin_user, created_at: 2.days.ago)
-
-
1
get :index, params: { q: { created_at_gteq: 2.days.ago, created_at_lteq: 1.day.ago } }
-
-
1
expect(assigns(:admin_users)).to include(user2)
-
1
expect(assigns(:admin_users)).not_to include(user1)
-
end
-
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::CustomAdsController, type: :controller do
-
1
render_views
-
-
1
before do
-
11
@admin = FactoryBot.create(:admin_user)
-
11
sign_in @admin
-
11
@advertisement = FactoryBot.create(:advertisement)
-
11
@strftime = '%B %d, %Y %H:%M'
-
11
@strftime_1 = "%Y-%m-%d 00:00:00"
-
11
@strftime_2 = "%Y-%m-%d 23:59:59"
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@advertisement.name)
-
1
expect(response.body).to include(@advertisement.description&.truncate(30))
-
1
expect(response.body).to include(@advertisement.duration)
-
1
expect(response.body).to include(@advertisement.start_at.strftime(@strftime))
-
1
expect(response.body).to include(@advertisement.expire_at.strftime(@strftime))
-
-
1
expect(response.body).to include(@advertisement.status)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by name' do
-
1
get :index, params: { q: { name_cont: @advertisement.name } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
-
1
it 'filters by description' do
-
1
get :index, params: { q: { description_cont: @advertisement.description } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
-
1
it 'filters by status' do
-
1
get :index, params: { q: { status_eq: 1 } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
-
1
it 'filters by start_at' do
-
1
get :index, params: { q: { start_at_gteq: @advertisement.start_at.strftime(@strftime_1), start_at_lteq: @advertisement.start_at.strftime(@strftime_2) } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
-
1
it 'filters by expire_at' do
-
1
get :index, params: { q: { expire_at_gteq: @advertisement.expire_at.strftime(@strftime_1), expire_at_lteq: @advertisement.expire_at.strftime(@strftime_2) } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq: @advertisement.created_at.strftime(@strftime_1), created_at_lteq: @advertisement.created_at.strftime(@strftime_2) } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq: @advertisement.updated_at.strftime(@strftime_1), updated_at_lteq: @advertisement.updated_at.strftime(@strftime_2) } }
-
1
expect(assigns(:custom_ads)).to include(@advertisement)
-
end
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
-
1
context 'with invalid dates' do
-
1
it 'does not allow creation if expire_at is before start_at' do
-
advertisement_params = {
-
1
name: 'Advertisement 1',
-
description: 'Description 1',
-
duration: 25,
-
start_at: Time.now,
-
expire_at: Time.now - 1.day
-
}
-
-
1
post :create, params: { advertisement: advertisement_params }
-
-
1
expect(assigns(:custom_ads).errors[:expire_at]).to include('Expiry date should be after the start date')
-
end
-
end
-
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template with advertisement details' do
-
1
get :show, params: { id: @advertisement.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(@advertisement.name)
-
1
expect(response.body).to include(@advertisement.description)
-
1
expect(response.body).to include(@advertisement.duration)
-
1
expect(response.body).to include(@advertisement.start_at.strftime(@strftime))
-
1
expect(response.body).to include(@advertisement.expire_at.strftime(@strftime))
-
-
1
expect(response.body).to include(@advertisement.status)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::AuthorFavoriteBooksController, type: :controller do
-
1
render_views
-
-
1
before do
-
2
@admin = FactoryBot.create(:admin_user)
-
2
sign_in @admin
-
2
@seller = create(:account, user_type: 'seller')
-
2
@catalogues = create_list(:catalogue,8, seller: @seller)
-
2
favorite_book_catalogues_attributes = @catalogues.map do |catalogue|
-
16
{ catalogue_id: catalogue.id }
-
end
-
2
@author_favorite_book = create(:author_favorite_book, title: 'Title1', favorite_book_catalogues_attributes: favorite_book_catalogues_attributes)
-
2
@params_tp = {title: 'Title1', favorite_book_catalogues_attributes: favorite_book_catalogues_attributes}
-
end
-
-
1
describe "GET #show" do
-
1
it "returns http success" do
-
1
get :show, params: { id: @author_favorite_book.id }
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::BannersController, type: :controller do
-
1
render_views
-
-
18
let(:admin_user) { create(:admin_user) }
-
-
1
before do
-
17
BxBlockDashboard::BannerGroup.all.delete_all
-
17
sign_in admin_user
-
17
@category = create(:category)
-
17
@subcategory = create(:sub_category, category: @category)
-
17
@catalogue = create(:catalogue)
-
17
@deal = create(:deal)
-
17
@banner_group = create(:banner_group, group_name: 'middle_group_2')
-
17
@banner_group2 = create(:banner_group, group_name: 'footer_group_1')
-
17
@banner = create(:banner, category: @category, banner_group: @banner_group2 )
-
17
@banner1 = create(:banner, catalogue: @catalogue )
-
17
@banner2 = create(:banner, sub_category: @subcategory, banner_group: @banner_group )
-
17
@banner3 = create(:banner, deal: @deal)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'not to have status 503' do
-
1
get :index
-
-
1
expect(response.body).not_to include("Service Unavailable")
-
end
-
-
1
it 'assigns @banners' do
-
1
get :index
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by title' do
-
1
get :index, params: { q: { title_cont: @banner.title } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by description' do
-
1
get :index, params: { q: { description_cont: @banner.description } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by button_text' do
-
1
get :index, params: { q: { button_text_cont: @banner.button_text } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
# it 'filters by button_link' do
-
# get :index, params: { q: { button_link_cont: @banner.button_link } }
-
# expect(assigns(:banners)).to include(@banner)
-
# end
-
-
1
it 'filters by banner_group_id' do
-
1
get :index, params: { q: { banner_group_id_eq: @banner.banner_group_id } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by category' do
-
1
get :index, params: { q: { category_id_eq: @banner.category_id } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by deal' do
-
1
get :index, params: { q: { deal_id_eq: @banner3.deal_id } }
-
1
expect(assigns(:banners)).to include(@banner3)
-
end
-
-
1
it 'filters by sub_category_id' do
-
1
get :index, params: { q: { sub_category_id_eq: @banner2.sub_category_id } }
-
1
expect(assigns(:banners)).to include(@banner2)
-
end
-
-
1
it 'filters by catalogue_id' do
-
1
get :index, params: { q: { catalogue_id_eq: @banner1.catalogue_id } }
-
1
expect(assigns(:banners)).to include(@banner1)
-
end
-
-
1
it 'filters by section' do
-
1
get :index, params: { q: { section_eq: @banner.section } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by banner_type' do
-
1
get :index, params: { q: { banner_type_eq: 1 } }
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: {
-
q: {
-
created_at_gteq: @banner.created_at.strftime("%Y-%m-%d 00:00:00"),
-
created_at_lteq: @banner.created_at.strftime("%Y-%m-%d 23:59:59")
-
}
-
}
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: {
-
q: {
-
updated_at_gteq: @banner.updated_at.strftime("%Y-%m-%d 00:00:00"),
-
updated_at_lteq: @banner.updated_at.strftime("%Y-%m-%d 23:59:59")
-
}
-
}
-
1
expect(assigns(:banners)).to include(@banner)
-
end
-
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @banner.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:banners)).to eq(@banner)
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: @banner.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ProductBarcodesController, type: :controller do
-
1
render_views
-
3
let(:admin_user) { create(:admin_user) }
-
2
let(:barcode) { create(:barcode) }
-
-
1
before do
-
2
sign_in admin_user
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
it 'updates the status of barcode' do
-
1
patch :update, params: { id: barcode.id, barcode: { status: false } }
-
1
barcode.reload
-
1
expect(barcode.status).to eq(false)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::BrandsController, type: :controller do
-
1
render_views
-
-
1
before do
-
14
@admin = FactoryBot.create(:admin_user)
-
14
sign_in @admin
-
14
@brands = create_list(:brand, 2)
-
14
@brand_c = create(:brand)
-
14
@catalogue = create(:catalogue, brand: @brand_c)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@brands.first.brand_name)
-
1
expect(response.body).to include(@brands.first.brand_year.to_s)
-
1
expect(response.body).to include(@brands.first.approve.to_s)
-
1
expect(response.body).to include(@brands.first.restricted.to_s)
-
1
expect(response.body).to include(@brands.first.gated.to_s)
-
1
expect(response.body).to include(@brands.first.created_at.strftime('%B %d, %Y %H:%M'))
-
1
expect(response.body).to include(@brands.first.updated_at.strftime('%B %d, %Y %H:%M'))
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by brand name' do
-
1
get :index, params: { q: { brand_name_cont: @brands.first.brand_name } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by brand year' do
-
1
get :index, params: { q: { brand_year_eq: @brands.first.brand_year } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by brand website' do
-
1
get :index, params: { q: { brand_website_cont: @brands.first.brand_website } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by approve' do
-
1
get :index, params: { q: { approve_eq: @brands.first.approve } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by restricted' do
-
1
@brands.first.update(restricted: true)
-
1
get :index, params: { q: { approve_eq: @brands.first.restricted } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by gated' do
-
1
@brands.first.update(gated: true)
-
1
get :index, params: { q: { approve_eq: @brands.first.gated } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq: @brands.first.created_at.strftime("%Y-%m-%d 00:00:00"), created_at_lteq: @brands.first.created_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq: @brands.first.updated_at.strftime("%Y-%m-%d 00:00:00"), updated_at_lteq: @brands.first.updated_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:brands)).to include(@brands.first)
-
end
-
end
-
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @brands.first.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(@brands.first.brand_name)
-
1
expect(response.body).to include(@brands.first.brand_year.to_s)
-
1
expect(response.body).to include(@brands.first.brand_website)
-
1
expect(response.body).to include("Yes")
-
end
-
end
-
-
1
describe 'PUT#update' do
-
1
it 'update a brand' do
-
1
@brand_c.update(approve: false)
-
1
@brand_c.update(approve: true)
-
1
put :update, params: {id: @brand_c.id, approve: true}
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'DELETE destroy' do
-
1
it 'flash error of association' do
-
1
get :destroy, params: { id: @brand_c.id }
-
1
expect(response).to redirect_to(admin_brands_path)
-
1
expect(flash['alert']).to include("Cannot delete brand because it is associated with products or store.")
-
end
-
-
1
it 'renders notice success' do
-
1
@catalogue.destroy
-
1
get :destroy, params: { id: @brand_c.id }
-
1
expect(response).to redirect_to(admin_brands_path)
-
1
expect(flash[:notice]).to include('Brand deleted successfully.')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::BuyerAccountsController, type: :controller do
-
1
render_views
-
1
before do
-
12
@admin = FactoryBot.create(:admin_user)
-
12
sign_in @admin
-
12
@account = create(:account, user_type: 'buyer')
-
end
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response).to have_http_status(200)
-
1
expect(response.body).to include(@account.email)
-
1
expect(response.body).to include(@account.first_name)
-
1
expect(response.body).to include(@account.last_name)
-
1
expect(response.body).to include(@account.user_type)
-
1
expect(response.body).to include(@account.full_phone_number)
-
1
expect(response.body).to include(@account.activated.to_s)
-
1
expect(response.body).to include(@account.language)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by first name' do
-
1
get :index, params: { q: { first_name_cont: @account.first_name } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by last name' do
-
1
get :index, params: { q: { last_name_cont: @account.last_name } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by full phone number' do
-
1
get :index, params: { q: { full_phone_number_cont: @account.full_phone_number } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by email' do
-
1
get :index, params: { q: { email_cont: @account.email } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by language' do
-
1
get :index, params: { q: { language_eq: @account.language } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by activated' do
-
1
get :index, params: { q: { activated_eq: @account.activated } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by created date range' do
-
1
get :index, params: { q: { created_at_gteq: @account.created_at.strftime("%Y-%m-%d 00:00:00"), created_at_lteq: @account.created_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
-
1
it 'filters by updated date range' do
-
1
get :index, params: { q: { updated_at_gteq: @account.updated_at.strftime("%Y-%m-%d 00:00:00"), updated_at_lteq: @account.updated_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:buyer_accounts)).to include(@account)
-
end
-
end
-
end
-
-
1
describe 'GET show' do
-
3
let(:account) { create(:account) }
-
-
1
it 'renders the show template' do
-
1
get :show, params: { id: account.id }
-
1
expect(response).to render_template(:show)
-
end
-
-
1
it 'assigns the requested account to @account' do
-
1
get :show, params: { id: account.id }
-
1
expect(assigns(:buyer_account)).to eq(account)
-
end
-
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::CatalogueContentsController, type: :controller do
-
1
render_views
-
3
let(:admin_user) { create(:admin_user) }
-
2
let(:catalogue_content) { create(:catalogue_content) }
-
-
1
before do
-
2
sign_in admin_user
-
end
-
-
1
describe "GET new" do
-
1
it "displays the new catalogue content form" do
-
1
get :new
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
it 'updates the status of catalogue content' do
-
1
patch :update, params: { id: catalogue_content.id, catalogue_content: { status: false } }
-
1
catalogue_content.reload
-
1
expect(catalogue_content.status).to eq(false)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ProductOffersController, type: :controller do
-
1
render_views
-
3
let(:admin_user) { create(:admin_user) }
-
2
let(:catalogue_offer) { create(:catalogue_offer) }
-
-
1
before do
-
2
sign_in admin_user
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
it 'updates the status of catalogue offer' do
-
1
patch :update, params: { id: catalogue_offer.id, catalogue_offer: { status: false } }
-
1
catalogue_offer.reload
-
1
expect(catalogue_offer.status).to eq(false)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ProductsController, type: :controller do
-
1
render_views
-
-
30
let(:admin_user) { create(:admin_user) }
-
30
let(:account) {create(:account, user_type: 'seller')}
-
30
let(:category) { create(:category) }
-
30
let(:subcategory) {create(:sub_category, category: category) }
-
30
let(:minicategory) { create(:mini_category, sub_category: subcategory) }
-
30
let(:microcategory) { create(:micro_category,mini_category: minicategory) }
-
30
let!(:catalogue) { create(:catalogue, product_image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg")), category: category,sub_category: subcategory,mini_category: minicategory, micro_category: microcategory, seller: account) }
-
30
let!(:product_content) {create(:product_content, catalogue: catalogue)}
-
30
let!(:deal) { create(:deal) }
-
30
let!(:deal_catalogue) { create(:deal_catalogue, deal: deal, catalogue: catalogue,seller: account) }
-
3
let(:barcode) { create(:barcode, catalogue: catalogue) }
-
2
let(:catalogue_offer) { create(:catalogue_offer, catalogue: catalogue, barcode: barcode) }
-
30
let!(:archived_catalogue) { create(:catalogue, content_status: 'archived', category: category, sub_category: subcategory, mini_category: minicategory, micro_category: microcategory) }
-
-
-
1
before do
-
29
sign_in admin_user
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
get :index
-
1
expect(response).to be_successful
-
end
-
-
1
it 'displays catalogue data in response body' do
-
1
get :index
-
1
expect(response.body).to include(catalogue.sku)
-
1
expect(response.body).to include(catalogue.product_title)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by category' do
-
1
get :index, params: { q: { category_id_eq: catalogue.category_id } }
-
1
expect(assigns(:products).last.category_id).to eq(catalogue.category_id)
-
end
-
-
1
it 'filters by brand' do
-
1
get :index, params: { q: { brand_id_eq: catalogue.brand_id } }
-
1
expect(assigns(:products).last.brand_id).to eq(catalogue.brand_id)
-
end
-
-
1
it 'filters by sub-category' do
-
1
get :index, params: { q: { sub_category_id_eq: catalogue.sub_category_id } }
-
1
expect(assigns(:products).last.sub_category_id).to eq(catalogue.sub_category.id)
-
end
-
-
1
it 'filters by mini-category' do
-
1
get :index, params: { q: { mini_category_id_eq: catalogue.mini_category_id } }
-
1
expect(assigns(:products).last.mini_category_id).to eq(catalogue.mini_category.id)
-
end
-
-
1
it 'filters by micro-category' do
-
1
get :index, params: { q: { micro_category_id_eq: catalogue.micro_category_id } }
-
1
expect(assigns(:products).last.micro_category_id).to eq(catalogue.micro_category.id)
-
end
-
-
1
it 'filters by deal catalogues' do
-
1
get :index, params: { q: { deal_catalogues_id_eq: deal_catalogue.id } }
-
1
expect(assigns(:products).last.deal_catalogues.first.id).to eq(deal_catalogue.id)
-
end
-
-
1
it 'filters by catalogue offer' do
-
1
get :index, params: { q: { catalogue_offer_id_eq: catalogue_offer.id } }
-
1
expect(assigns(:products).last.catalogue_offer.id).to eq(catalogue_offer.id)
-
end
-
-
1
it 'filters by barcode' do
-
1
get :index, params: { q: { barcode_id_eq: barcode.id } }
-
1
expect(assigns(:products).last.barcode.id).to eq(barcode.id)
-
end
-
-
1
it 'filters by SKU' do
-
1
get :index, params: { q: { sku_or_product_variant_group_product_sku_cont: catalogue.sku } }
-
1
expect(assigns(:products).last.sku).to include(catalogue.sku)
-
end
-
-
1
it 'filters by BESKU' do
-
1
get :index, params: { q: { besku_or_product_variant_group_product_besku_cont: catalogue.besku } }
-
1
expect(assigns(:products).last.besku).to include(catalogue.besku)
-
end
-
-
1
it 'filters by product title' do
-
1
get :index, params: { q: { product_title_cont: catalogue.product_title } }
-
1
expect(assigns(:products).last.product_title).to include(catalogue.product_title)
-
end
-
-
1
it 'filters by status' do
-
1
get :index, params: { q: { status_eq: catalogue.status } }
-
1
expect(assigns(:products).last.status).to eq(catalogue.status)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq_datetime: catalogue.created_at.strftime("%Y-%m-%d 00:00:00"), created_at_lteq_datetime: catalogue.created_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:products).last.created_at.to_date.to_s).to eq(catalogue.created_at.to_date.to_s)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq_datetime: catalogue.updated_at.strftime("%Y-%m-%d 00:00:00"), updated_at_lteq_datetime: catalogue.updated_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:products).last.updated_at.to_date.to_s).to eq(catalogue.updated_at.to_date.to_s)
-
end
-
-
end
-
end
-
-
1
describe 'PUT #archive' do
-
1
it 'archives the catalogue item' do
-
1
put :archive, params: {id: catalogue.id }
-
1
expect(response).to redirect_to(admin_products_path)
-
1
catalogue.reload
-
1
expect(catalogue.content_status).to eq('archived')
-
end
-
end
-
-
1
describe 'PUT #unarchives' do
-
1
before do
-
1
catalogue.update(content_status: 'archived')
-
end
-
-
1
it 'unarchives the catalogue item' do
-
1
put :unarchive, params: {id: catalogue.id}
-
1
expect(response).to redirect_to(admin_products_path)
-
1
catalogue.reload
-
1
expect(catalogue.content_status).to eq('under_review')
-
end
-
end
-
-
1
describe 'Scopes' do
-
1
it 'includes non-archived catalogues in the default scope' do
-
1
get :index
-
1
expect(assigns(:products)).to include(catalogue)
-
end
-
-
1
it 'includes only archived catalogues in the archived scope' do
-
1
catalogue.update(content_status: 'archived')
-
1
get :index, params: {scope: 'archived'}
-
1
expect(assigns(:products)).to include(catalogue)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: catalogue.id }
-
1
expect(response).to be_successful
-
end
-
-
1
it 'returns a success show response' do
-
1
variant = create(:catalogue, product_image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg")), category: category,sub_category: subcategory,mini_category: minicategory, micro_category: microcategory, is_variant: true, parent_product: catalogue)
-
1
get :show, params: { id: variant.id }
-
1
expect(response).to be_successful
-
1
expect(response.body).to include('Parent Product')
-
-
end
-
-
1
it 'shows the Unarchive link' do
-
1
get :show, params: { id: archived_catalogue.id }
-
1
expect(response.body).to include('Unarchive')
-
end
-
-
1
it 'displays catalogue details in response body' do
-
1
content = create(:catalogue_content, catalogue: catalogue)
-
1
offer = create(:catalogue_offer, catalogue: catalogue)
-
1
code = create(:barcode, catalogue: catalogue)
-
1
get :show, params: { id: catalogue.id }
-
1
expect(response.body).to include(catalogue.sku)
-
1
expect(response.body).to include(catalogue.product_title)
-
1
expect(response.body).to include(deal_catalogue.deal.deal_name)
-
1
expect(response.body).to include(product_content.product_title)
-
1
expect(response.body).to include(product_content.whats_in_the_package)
-
1
expect(response.body).to include('Edit')
-
end
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'returns a success update response' do
-
1
get :edit, params: { id: catalogue.id }
-
1
expect(response).to be_successful
-
1
expect(response.body).to include(Rails.application.routes.url_helpers.rails_blob_path(catalogue.product_image, only_path: true))
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
it 'returns a success update response via email #accepted' do
-
1
catalogue.update(content_status: 'under_review')
-
1
patch :update, params: { id: catalogue.id, catalogue: { content_status: "accepted", status: true } }
-
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
-
1
it 'returns a success update response via email #rejected' do
-
1
catalogue.update(content_status: 'under_review')
-
1
patch :update, params: { id: catalogue.id, catalogue: { content_status: "rejected" } }
-
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
end
-
-
1
describe 'validations' do
-
2
let(:product_image) { fixture_file_upload(Rails.root.join('spec/fixtures/files/document.pdf'), 'text/pdf') }
-
2
let(:catalogue1) { build(:catalogue, product_image: product_image) }
-
-
1
context 'with an invalid image type' do
-
1
it 'is not valid' do
-
1
expect(catalogue1).not_to be_valid
-
1
expect(catalogue1.errors[:product_image]).to include('must be a JPEG/JPG/PNG/WebP file')
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::CategoriesController, type: :controller do
-
1
render_views
-
10
let(:admin_user) { create(:admin_user) }
-
10
let!(:category) { create(:category) }
-
-
1
before do
-
9
sign_in admin_user
-
end
-
-
1
describe "GET index" do
-
1
it "displays a list of categories" do
-
1
category2 = create(:category, name: Faker::Lorem.word + Faker::Lorem.word)
-
1
get :index
-
1
expect(response).to have_http_status(:success)
-
end
-
-
1
it 'filters by category name' do
-
1
get :index, params: { q: { name_cont: category.name } }
-
1
expect(assigns(:categories)).to include(category)
-
end
-
-
1
it 'filters by subcategories' do
-
1
sub_category = create(:sub_category, category: category)
-
1
get :index, params: { q: { sub_categories_id_eq: sub_category.id } }
-
1
expect(assigns(:categories)).to include(category)
-
end
-
-
1
it 'filters by mini categories' do
-
1
mini_category = create(:mini_category, sub_category: create(:sub_category, category: category))
-
1
get :index, params: { q: { mini_categories_id_eq: mini_category.id } }
-
1
expect(assigns(:categories)).to include(category)
-
end
-
-
1
it 'filters by micro categories' do
-
1
micro_category = create(:micro_category, mini_category: create(:mini_category, sub_category: create(:sub_category, category: category)))
-
1
get :index, params: { q: { micro_categories_id_eq: micro_category.id } }
-
1
expect(assigns(:categories)).to include(category)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq_datetime: category.created_at.strftime("%Y-%m-%d 00:00:00"), created_at_lteq_datetime: category.created_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:categories)).to include(category)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq_datetime: category.updated_at.strftime("%Y-%m-%d 00:00:00"), updated_at_lteq_datetime: category.updated_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:categories)).to include(category)
-
end
-
-
end
-
-
1
describe "GET new" do
-
1
it "displays the new category form" do
-
1
get :new
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template and assigns the category' do
-
1
sub_category = create(:sub_category, category: category)
-
1
mini_category = create(:mini_category, sub_category: sub_category)
-
1
micro_category = create(:micro_category, mini_category: mini_category)
-
1
custom_field = create(:custom_field, fieldable: category)
-
1
sub_custom_field = create(:custom_field, fieldable: sub_category)
-
1
mini_custom_field = create(:custom_field, fieldable: mini_category)
-
1
micro_custom_field = create(:custom_field, fieldable: micro_category)
-
-
-
1
get :show, params: { id: category.id }
-
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:category).sub_categories.last.custom_fields).to include(sub_custom_field)
-
1
expect(assigns(:category).sub_categories.last.mini_categories.last.custom_fields).to include(mini_custom_field)
-
1
expect(assigns(:category).sub_categories.last.mini_categories.last.micro_categories.last.custom_fields).to include(micro_custom_field)
-
1
expect(assigns(:category)).to eq(category)
-
1
expect(assigns(:category).created_at).to eq(category.created_at)
-
1
expect(assigns(:category).custom_fields).to include(custom_field)
-
1
expect(assigns(:category).sub_categories).to include(sub_category)
-
1
expect(assigns(:category).sub_categories.last.mini_categories).to include(mini_category)
-
1
expect(assigns(:category).sub_categories.last.mini_categories.last.micro_categories).to include(micro_category)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ContactUsController, type: :controller do
-
1
render_views
-
-
-
1
before do
-
4
@admin = FactoryBot.create(:admin_user)
-
4
@contact = FactoryBot.create(:contact)
-
4
sign_in @admin
-
4
@contacts = create_list(:contact, 2)
-
4
@no_image = 'No image yet'
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
@contacts.last.image.detach
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
@contacts.each do |contact|
-
2
expect(response.body).to include(contact.title)
-
2
expect(response.body).to include(contact.description)
-
2
expect(response.body).to include(contact.email)
-
2
expect(response.body).to include(contact.contact_type)
-
2
expect(response.body).to include(@no_image)
-
end
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'displays "No image yet" when the image is not attached' do
-
1
@contact.image.detach
-
1
get :show, params: { id: @contact.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(@no_image)
-
end
-
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: @contact.id }
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::CouponsController, type: :controller do
-
1
render_views
-
7
let(:admin_user) { create(:admin_user) }
-
7
let!(:coupon) { create(:coupon) }
-
1
let(:valid_attributes) do
-
{
-
2
title: Faker::Lorem.unique.sentence,
-
code: SecureRandom.hex(8),
-
discount: Faker::Number.between(from: 5, to: 50),
-
valid_from: Faker::Date.backward(days: 10),
-
valid_to: Faker::Date.forward(days: 10)
-
}
-
end
-
-
1
before do
-
6
sign_in admin_user
-
end
-
-
1
describe "POST #create coupon" do
-
1
context "coupon with valid attributes" do
-
1
it "creates a new coupon record" do
-
1
post :create, params: { coupon: valid_attributes }
-
1
expect(response).to have_http_status(:success)
-
end
-
-
1
it "creates a new Coupon record" do
-
1
get :new
-
1
expect(response).to have_http_status(:success)
-
end
-
end
-
end
-
-
1
describe "UPDATE#Coupon" do
-
1
it 'should update coupon' do
-
1
patch :update, params: {id: coupon.id, coupon: valid_attributes }
-
1
expect(response).to have_http_status(302)
-
end
-
end
-
-
1
describe "DELETE #Coupon" do
-
1
it 'should delete coupon' do
-
1
delete :delete_coupon, params: { id: coupon.id }
-
1
expect(response).to have_http_status(302)
-
end
-
end
-
-
1
describe "INDEX#Coupon" do
-
1
it 'should index coupons' do
-
1
get :index
-
1
expect(response).to have_http_status :success
-
end
-
end
-
-
1
describe "SHOW#Coupon" do
-
1
it 'should show coupon' do
-
1
get :show, params: {id: coupon.id}
-
1
expect(response).to have_http_status :success
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::DashboardController, type: :controller do
-
1
render_views
-
-
1
it 'redirects to login' do
-
1
get :index
-
-
1
expect(response).to redirect_to(new_admin_user_session_path)
-
end
-
-
1
context 'when logged in as admin' do
-
2
let(:admin) { create(:admin_user) }
-
-
2
before { sign_in(admin) }
-
-
1
it 'renders page' do
-
1
get :index
-
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include('Welcome to Active Admin. This is the default dashboard page')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SellerDealsController, type: :controller do
-
1
render_views
-
12
let(:admin_user) { create(:admin_user) }
-
12
let(:account) {create(:account, user_type: 'seller')}
-
12
let!(:deal) { create(:deal) }
-
12
let!(:catalogue) { create(:catalogue) }
-
12
let!(:deal_catalogue) { create(:deal_catalogue, deal: deal, catalogue: catalogue,seller: account, status: 0 ) }
-
-
1
before do
-
11
sign_in admin_user
-
end
-
-
1
describe 'GET #show' do
-
1
it 'displays deal catalogue details' do
-
1
get :show, params: { id: deal_catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(deal.deal_name)
-
1
expect(response.body).to include(catalogue.sku)
-
1
expect(response.body).to include(deal_catalogue.status)
-
1
expect(response.body).to include(deal_catalogue.deal_price.to_s)
-
1
expect(response.body).to include(deal_catalogue.created_at.strftime('%B %d, %Y %H:%M'))
-
1
expect(response.body).to include(deal_catalogue.updated_at.strftime('%B %d, %Y %H:%M'))
-
-
end
-
end
-
-
-
1
describe 'GET #index' do
-
1
it 'displays the list of deal catalogues' do
-
1
get :index
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(deal.deal_name)
-
1
expect(response.body).to include(catalogue.sku)
-
1
expect(response.body).to include(deal_catalogue.status)
-
1
expect(response.body).to include(deal_catalogue.deal_price.to_s)
-
end
-
-
1
it 'filters by deal name' do
-
1
get :index, params: { q: { deal_id_eq: deal.id } }
-
1
expect(assigns(:seller_deals)).to include(deal_catalogue)
-
end
-
-
1
it 'filters by catalogue SKU' do
-
1
get :index, params: { q: { catalogue_sku_contains: catalogue.sku } }
-
1
expect(assigns(:seller_deals)).to include(deal_catalogue)
-
end
-
-
1
it 'filters by status' do
-
1
get :index, params: { q: { status_eq: deal_catalogue.status } }
-
1
expect(assigns(:seller_deals)).to include(deal_catalogue)
-
end
-
-
1
it 'filters by deal price' do
-
1
get :index, params: { q: { deal_price_eq: deal_catalogue.deal_price } }
-
1
expect(assigns(:seller_deals)).to include(deal_catalogue)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq_datetime: deal_catalogue.created_at.strftime('%Y-%m-%d 00:00:00'), created_at_lteq_datetime: deal_catalogue.created_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:seller_deals)).to include(deal_catalogue)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq_datetime: deal_catalogue.updated_at.strftime('%Y-%m-%d 00:00:00'), updated_at_lteq_datetime: deal_catalogue.updated_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:seller_deals)).to include(deal_catalogue)
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'displays the edit form for a deal catalogue' do
-
1
get :edit, params: { id: deal_catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include('Edit Seller Deal')
-
1
expect(response.body).to include(deal_catalogue.status)
-
1
expect(response.body).to include(deal_catalogue.deal_price.to_s)
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
it 'updates the deal catalogue status and redirects back to the deal show page' do
-
1
new_status = 'approved'
-
-
1
put :update, params: { id: deal_catalogue.id, 'deal_catalogue' => { 'status' => new_status, deal_id: deal.id } }
-
-
1
expect(response).to redirect_to(admin_deal_path(deal))
-
1
expect(deal_catalogue.reload.status).to eq(new_status)
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
it 'updates the deal catalogue status and redirects back to the deal show page' do
-
1
new_status = 'review'
-
1
new_deal_price = 150.0
-
-
1
put :update, params: {
-
id: deal_catalogue.id,
-
deal_catalogue: {
-
status: new_status,
-
seller_id: account.id,
-
deal_id: deal.id,
-
deal_price: new_deal_price
-
}
-
}
-
-
1
expect(response).to redirect_to(admin_deal_path(deal))
-
1
expect(deal_catalogue.reload.status).to eq('review')
-
1
expect(deal_catalogue.reload.seller_id).to eq(account.id)
-
1
expect(deal_catalogue.reload.deal_price).to eq(new_deal_price)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::DealsController, type: :controller do
-
1
render_views
-
11
let(:admin_user) { create(:admin_user) }
-
11
let(:account) {create(:account, user_type: 'seller')}
-
11
let!(:deal) { create(:deal) }
-
11
let!(:catalogue) { create(:catalogue) }
-
11
let!(:deal_catalogue) { create(:deal_catalogue, deal: deal, catalogue: catalogue , seller: account) }
-
-
1
before do
-
10
sign_in admin_user
-
end
-
-
1
describe 'GET #index' do
-
1
it 'displays the list of deals' do
-
1
get :index
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(deal.deal_name)
-
1
expect(response.body).to include(deal.deal_code)
-
1
expect(response.body).to include(deal.discount_type)
-
1
expect(response.body).to include(deal.discount_value.to_s)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'displays deal details and related deal catalogues' do
-
-
1
get :show, params: { id: deal.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(deal.deal_name)
-
1
expect(response.body).to include(deal.deal_code)
-
1
expect(response.body).to include(deal_catalogue.seller_sku)
-
# expect(response.body).to include(deal_catalogue.product_title)
-
1
expect(response.body).to include(deal_catalogue.deal_price.to_s)
-
1
expect(response.body).to include(deal_catalogue.status.capitalize)
-
1
expect(response.body).to include('Edit Status')
-
1
expect(response.body).to include("Deal Catalogues")
-
end
-
end
-
-
1
describe 'filters' do
-
1
it 'filters by deal name' do
-
1
get :index, params: { q: { deal_name_eq: deal.deal_name } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
-
1
it 'filters by deal code' do
-
1
get :index, params: { q: { deal_code_eq: deal.deal_code } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
-
1
it 'filters by start date' do
-
1
get :index, params: { q: { start_date_eq: deal.start_date } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
-
1
it 'filters by end date' do
-
1
get :index, params: { q: { end_date_eq: deal.end_date } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
-
1
it 'filters by status' do
-
1
get :index, params: { q: { status_eq: deal.status } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq_datetime: deal.created_at.strftime('%Y-%m-%d 00:00:00'), created_at_lteq_datetime: deal.created_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq_datetime: deal.updated_at.strftime('%Y-%m-%d 00:00:00'), updated_at_lteq_datetime: deal.updated_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:deals)).to include(deal)
-
end
-
end
-
-
1
describe "GET new" do
-
1
it "displays the new deal form" do
-
1
get :new
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::DeliveryRequestsController, type: :controller do
-
1
render_views
-
-
9
let(:admin_user) { create(:admin_user) }
-
9
let(:account) { create(:account, user_type: 'seller') }
-
9
let(:customer) { create(:account, user_type: 'buyer') }
-
9
let(:warehouse) { create(:warehouse, account: account) }
-
9
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Processing')}
-
9
let(:order) {create(:shopping_cart_order, customer: customer, order_status: order_status )}
-
2
let(:delivery_request) { create(:delivery_request, warehouse: warehouse, seller: account, order: order) }
-
1
let(:valid_attributes) { {
-
1
warehouse_name: warehouse.warehouse_name,
-
seller_id: account.id,
-
order_number: order.order_number,
-
address_1: '123 Main St',
-
address_2: 'Apt 456',
-
status: 'Pending'
-
}}
-
-
1
before do
-
8
sign_in admin_user
-
8
order.update(order_status: order_status)
-
8
@delivery_request_inx = FactoryBot.create(:delivery_request, warehouse: warehouse, seller: account, order: order)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success response index' do
-
1
get :index
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@delivery_request_inx.warehouse_name)
-
1
expect(response.body).to include(@delivery_request_inx.order_number)
-
1
expect(response.body).to include(@delivery_request_inx.status)
-
1
expect(response.body).to include(admin_seller_account_path(@delivery_request_inx.seller))
-
end
-
-
1
it 'returns a success response and filters by warehouse_name' do
-
-
1
get :index, params: { q: { warehouse_name_eq: @delivery_request_inx.warehouse_name } }
-
-
1
expect(assigns(:delivery_requests)).to include(@delivery_request_inx)
-
end
-
-
1
it 'returns a success response and filters by order_number' do
-
-
1
get :index, params: { q: { order_number_eq: order.order_number } }
-
-
1
expect(assigns(:delivery_requests)).to include(@delivery_request_inx)
-
end
-
-
1
it 'returns a success response and filters by status' do
-
-
1
get :index, params: { q: { status_eq: 'pending' } }
-
-
1
expect(assigns(:delivery_requests)).to include(@delivery_request_inx)
-
end
-
-
1
it 'returns a success response and filters by created_at' do
-
-
1
get :index, params: { q: { created_at_gteq: @delivery_request_inx.created_at.strftime("%Y-%m-%d 00:00:00"), created_at_lteq: @delivery_request_inx.created_at.strftime("%Y-%m-%d 23:59:59") } }
-
-
1
expect(assigns(:delivery_requests)).to include(@delivery_request_inx)
-
end
-
-
1
it 'returns a success response and filters by updated_at' do
-
-
1
get :index, params: { q: { updated_at_gteq: @delivery_request_inx.updated_at.strftime("%Y-%m-%d 00:00:00"), updated_at_lteq: @delivery_request_inx.updated_at.strftime("%Y-%m-%d 23:59:59") } }
-
-
1
expect(assigns(:delivery_requests)).to include(@delivery_request_inx)
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'returns a success response show' do
-
1
get :edit, params: { id: delivery_request.id }
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'with valid params' do
-
1
it 'creates a new delivery request with correct order and warehouse' do
-
1
expect {
-
1
post :create, params: { delivery_request: valid_attributes }
-
}.to change(BxBlockOrderManagement::DeliveryRequest, :count).by(1)
-
-
1
expect(BxBlockOrderManagement::DeliveryRequest.last.order_id).to eq(order.id)
-
1
expect(BxBlockOrderManagement::DeliveryRequest.last.warehouse_id).to eq(warehouse.id)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::GatedBrandsReqsController, type: :controller do
-
1
render_views
-
-
1
before do
-
5
@admin = FactoryBot.create(:admin_user)
-
5
sign_in @admin
-
5
@brand = create(:brand, gated: true)
-
5
@gated_brand = create(:gated_brand, brand: @brand)
-
5
@approved = "No"
-
5
@brand_id = "Brand ##{@brand.id}"
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@brand_id)
-
1
expect(response.body).to include(@approved)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by brand' do
-
1
get :index, params: { q: { brand_id_eq: @brand.id } }
-
1
expect(response.body).to include(@brand_id)
-
end
-
-
1
it 'filters by approved' do
-
1
get :index, params: { q: { approved_eq: @gated_brand.approved } }
-
1
expect(response.body).to include(@approved)
-
end
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @gated_brand.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(@brand_id)
-
1
expect(response.body).to include(@approved)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::MicroCategoriesController, type: :controller do
-
1
render_views
-
8
let!(:category) { create(:category, name: 'Test Category') }
-
8
let!(:sub_category) { create(:sub_category, name: 'Test Subcategory', category: category) }
-
8
let!(:mini_category) { create(:mini_category, name: 'Test Mini Category', sub_category: sub_category) }
-
8
let!(:micro_category) { mini_category.micro_categories.create(name: 'Test Micro Category') }
-
-
1
before do
-
7
@admin_user = create(:admin_user)
-
7
sign_in @admin_user
-
end
-
-
1
describe "GET new" do
-
1
it "displays the new micro category form" do
-
1
get :new
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'POST create' do
-
1
it 'creates a new micro category and redirects to the category show page' do
-
1
expect {
-
1
post :create, params: { micro_category: { name: 'New Micro Category', mini_category_id: mini_category.id } }
-
}.to change(BxBlockCategories::MicroCategory, :count).by(1)
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(category))
-
end
-
-
1
it 'invalid params create a new micro category and redirects to the micro show page' do
-
1
expect {
-
1
post :create, params: { micro_category: { name: 'New Micro Category', parent_id: category.id } }
-
}.to change(BxBlockCategories::MicroCategory, :count).by(0)
-
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'PUT update' do
-
1
it 'updates the attributes of a micro category and redirects to the category show page' do
-
1
updated_name = 'Updated Micro Category'
-
-
1
put :update, params: { id: micro_category.id, micro_category: { name: updated_name, parent_id: category.id, mini_category_id: mini_category.id } }
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(category))
-
1
expect(micro_category.reload.name).to eq(updated_name)
-
end
-
-
1
it 'invalid params update the attributes of a micro category and redirects to the micro edit page' do
-
1
updated_name = 'Updated Micro Category'
-
-
1
put :update, params: { id: micro_category.id, micro_category: { name: updated_name, parent_id: category.id, mini_category_id: nil } }
-
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
1
describe 'Delete Destroy' do
-
1
it 'Destroy the attributes of a micro category and redirects to the category show page' do
-
-
1
delete :destroy, params: { id: micro_category.id }
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(category))
-
# expect(mini_category.reload.name).to eq(updated_name)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template and assigns the micro category' do
-
1
custom_field = create(:custom_field, fieldable: micro_category)
-
-
-
1
get :show, params: { id: micro_category.id }
-
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:micro_category)).to eq(micro_category)
-
1
expect(assigns(:micro_category).custom_fields).to include(custom_field)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::MiniCategoriesController, type: :controller do
-
1
render_views
-
8
let!(:category) { create(:category, name: 'Test Category') }
-
8
let!(:sub_category) { create(:sub_category, name: 'Test Subcategory', category: category) }
-
8
let!(:mini_category) { create(:mini_category, name: 'Test Mini Category', sub_category: sub_category) }
-
-
1
before do
-
7
@admin_user = create(:admin_user)
-
7
sign_in @admin_user
-
end
-
-
1
describe 'POST create' do
-
1
it 'creates a new mini category and redirects to the category show page' do
-
1
expect {
-
1
post :create, params: { mini_category: { name: 'New Mini Category', sub_category_id: sub_category.id } }
-
}.to change(BxBlockCategories::MiniCategory, :count).by(1)
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(category))
-
end
-
-
1
it ' invalid params to create a new mini category and redirects to the category show page' do
-
1
expect {
-
1
post :create, params: { mini_category: { name: 'New Mini Category',parent_id: category.id, sub_category_id: '' } }
-
}.to change(BxBlockCategories::MiniCategory, :count).by(0)
-
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'PUT update' do
-
1
it 'updates the attributes of a mini category and redirects to the category show page' do
-
1
updated_name = 'Updated Mini Category'
-
-
1
put :update, params: { id: mini_category.id, mini_category: { name: updated_name, sub_category_id: sub_category.id} }
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(category))
-
1
expect(mini_category.reload.name).to eq(updated_name)
-
end
-
-
1
it 'invalid params update the attributes of a mini category and redirects to the category show page' do
-
1
updated_name = 'Updated Mini Category'
-
-
1
put :update, params: { id: mini_category.id, mini_category: { name: updated_name, sub_category_id: nil } }
-
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template and assigns the mini category' do
-
1
custom_field = create(:custom_field, fieldable: mini_category)
-
-
-
1
get :show, params: { id: mini_category.id }
-
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:mini_category)).to eq(mini_category)
-
1
expect(assigns(:mini_category).custom_fields).to include(custom_field)
-
1
expect(assigns(:mini_category).sub_category.name).to eq(sub_category.name)
-
end
-
end
-
-
1
describe "GET new" do
-
1
it "displays the new mini category form" do
-
1
get :new
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'Delete destroy' do
-
1
it 'Destroy the attributes of a mini category and redirects to the category show page' do
-
-
1
delete :destroy, params: { id: mini_category.id }
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(category))
-
# expect(mini_category.reload.name).to eq(updated_name)
-
end
-
end
-
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::OrderItemsController, type: :controller do
-
1
render_views
-
-
2
let(:admin_user) { FactoryBot.create(:admin_user) }
-
2
let(:seller) { FactoryBot.create(:account, company_or_store_name: "byezzy") }
-
2
let(:customer) { FactoryBot.create(:account) }
-
2
let(:catalogue) { create(:catalogue, seller: seller) }
-
2
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'on_going') }
-
2
let(:order) { FactoryBot.create(:shopping_cart_order, customer: customer, order_status: order_status) }
-
2
let(:order_item) { FactoryBot.create(:shopping_cart_order_item, catalogue: catalogue, order: order) }
-
-
1
before do
-
1
sign_in admin_user
-
end
-
-
# describe 'GET #index' do
-
# it 'renders the index template' do
-
# get :index
-
# expect(response).to render_template(:index)
-
# end
-
# end
-
-
1
describe 'GET #show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: order_item.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(order_item.id.to_s)
-
1
expect(response.body).to include(order_item.quantity.to_s)
-
1
expect(response.body).to include(order_item.price.to_s)
-
1
expect(response.body).to include("Catalogue Details")
-
1
expect(response.body).to include(catalogue.id.to_s)
-
1
expect(response.body).to include(catalogue.sku)
-
1
expect(response.body).to include(catalogue.besku)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::OrderStatusesController, type: :controller do
-
1
render_views
-
1
let(:valid_attributes) do
-
{
-
1
name: Faker::Lorem.characters(number: 10).gsub(/\d/, '').upcase
-
}
-
end
-
1
before do
-
5
@admin = FactoryBot.create(:admin_user)
-
5
@order_status = FactoryBot.create(:order_status)
-
5
sign_in @admin
-
5
@order_statuses = create_list(:order_status, 2)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
@order_statuses.each do |order_status|
-
2
expect(response.body).to include(order_status.name)
-
end
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: @order_status.id }
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe "UPDATE#order status" do
-
1
it 'should update order status' do
-
1
put :update, params: {id: @order_status.id, order_status: valid_attributes }
-
1
expect(response).to have_http_status(302)
-
end
-
end
-
-
1
describe "DELETE #order status" do
-
1
it 'should delete order status' do
-
1
delete :destroy, params: { id: @order_status.id }
-
1
expect(response).to have_http_status(302)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::OrdersController, type: :controller do
-
1
render_views
-
-
8
let(:admin_user) { FactoryBot.create(:admin_user) }
-
1
let(:seller) { FactoryBot.create(:account, user_type: 'seller', company_or_store_name: "byezzy") }
-
8
let(:customer) { FactoryBot.create(:account, user_type: 'buyer') }
-
1
let(:catalogue) {create(:catalogue, seller: seller)}
-
3
let(:shipping_address) {create(:user_delivery_address, account: customer, is_default: true)}
-
8
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'on_going') }
-
3
let(:order) { FactoryBot.create(:shopping_cart_order, customer: customer, order_status: order_status, address_id: shipping_address.id) }
-
1
let(:order_items) {FactoryBot.create_list(:shopping_cart_order_item, 2, catalogue: catalogue, order: order)}
-
-
1
before do
-
7
sign_in admin_user
-
end
-
-
1
describe 'GET #index' do
-
1
before do
-
5
@orders = create_list(:shopping_cart_order,2,customer: customer, order_status: order_status)
-
5
@order_items = create_list(:shopping_cart_order_item,2,order: @orders.first, order_status: order_status)
-
end
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@orders.last.order_number.to_s)
-
1
expect(response.body).to include(@orders.last.total_items.to_s)
-
1
expect(response.body).to include("No")
-
end
-
-
1
it 'filters by order number' do
-
1
get :index, params: {q: {order_number_eq: @orders.first.order_number}}
-
1
expect(response.body).to include(@orders.first.order_number.to_s)
-
end
-
-
1
it 'filters by total items' do
-
1
get :index, params: {q: {total_items_eq: @orders.first.total_items}}
-
1
expect(response.body).to include(@orders.first.total_items.to_s)
-
end
-
-
1
it 'filters by order status' do
-
1
get :index, params: {q: {order_status_id_eq: @orders.first.order_status.id}}
-
1
expect(response.body).to include(@orders.first.order_status.status)
-
end
-
-
1
it 'filters by order item status' do
-
1
get :index, params: {q: {order_items_order_status_id_in: @orders.first.order_status.id}}
-
1
expect(response.body).to include(@orders.first.order_status.status)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: order.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(order.id.to_s)
-
1
expect(response.body).to include(order.total_fees.to_s)
-
1
expect(response.body).to include(order.total_tax.to_s)
-
1
expect(response.body).to include(order.final_price.to_s)
-
1
expect(response.body).to include("No")
-
1
expect(response.body).to include("Customer")
-
1
expect(response.body).to include("Sellers")
-
1
expect(response.body).to include("Shipping Address")
-
1
expect(response.body).to include("Order Items")
-
1
expect(response.body).to include("Catalogue")
-
1
seller_names = order.sellers.map { |seller| link_to(seller.full_name, admin_seller_account_path(seller)) }.join(', ')
-
1
expect(response.body).to include(seller_names)
-
1
address = order.shipping_address.attributes.slice(
-
'first_name', 'last_name', 'address_1', 'address_2',
-
'phone_number', 'state', 'city', 'zip_code', 'address_type'
-
).values.join(', ')
-
1
expect(response.body).to include(address)
-
1
expect(response.body).not_to include("Coupon Code")
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: order.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
end
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ByezzyProductsController, type: :controller do
-
1
render_views
-
-
12
let(:admin_user) { create(:admin_user) }
-
12
let(:category) { create(:category) }
-
12
let(:seller) { create(:account, user_type: 'seller') }
-
12
let(:parent_catalogue) {create(:parent_catalogue)}
-
12
let!(:catalogue) { create(:catalogue, product_image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg")), category: category, seller: seller, parent_catalogue: parent_catalogue) }
-
-
1
before do
-
11
sign_in admin_user
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
get :index
-
1
expect(response).to be_successful
-
end
-
-
1
it 'displays parent catalogue data in response body' do
-
1
parent_catalogue_i = create(:parent_catalogue,product_title: "test prod" )
-
1
get :index
-
1
expect(response.body).to include(parent_catalogue_i.sku)
-
1
expect(response.body).to include(parent_catalogue_i.product_title)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by category' do
-
1
get :index, params: { q: { category_id_eq: parent_catalogue.category_id } }
-
1
expect(assigns(:byezzy_products).last.category_id).to eq(parent_catalogue.category_id)
-
end
-
-
1
it 'filters by brand' do
-
1
get :index, params: { q: { brand_id_eq: parent_catalogue.brand_id } }
-
1
expect(assigns(:byezzy_products).last.brand_id).to eq(parent_catalogue.brand_id)
-
end
-
-
1
it 'filters by BESKU' do
-
1
get :index, params: { q: { besku_cont: parent_catalogue.besku } }
-
1
expect(assigns(:byezzy_products).last.besku).to include(parent_catalogue.besku)
-
end
-
-
1
it 'filters by product title' do
-
1
get :index, params: { q: { product_title_cont: parent_catalogue.product_title } }
-
1
expect(assigns(:byezzy_products).last.product_title).to include(parent_catalogue.product_title)
-
end
-
-
1
it 'filters by status' do
-
1
get :index, params: { q: { status_eq: parent_catalogue.status } }
-
1
expect(assigns(:byezzy_products).last.status).to eq(parent_catalogue.status)
-
end
-
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: parent_catalogue.id }
-
1
expect(response).to be_successful
-
end
-
-
1
it 'displays parent_catalogue details in response body' do
-
1
get :show, params: { id: parent_catalogue.id }
-
1
expect(response.body).to include(parent_catalogue.besku)
-
1
expect(response.body).to include(parent_catalogue.product_title)
-
1
expect(response.body).to include(catalogue.sku)
-
1
expect(response.body).to include(catalogue.seller.full_name)
-
end
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'returns a success update response' do
-
1
get :edit, params: { id: parent_catalogue.id }
-
1
expect(response).to be_successful
-
1
expect(response.body).to include(Rails.application.routes.url_helpers.rails_blob_path(parent_catalogue.product_image, only_path: true))
-
end
-
end
-
-
# describe 'PATCH #update' do
-
# it 'returns an unsuccessful update response with validation message' do
-
# patch :update, params: { id: parent_catalogue.id, parent_catalogue: { prod_model_no: 'ajhj' } }
-
-
-
# expect(flash[:error]).to include("should be uppercase alphanumeric and have a length between 5 and 13 characters")
-
# end
-
# end
-
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::TaxAndLegalPoliciesController, type: :controller do
-
1
render_views
-
-
1
before do
-
3
@admin = FactoryBot.create(:admin_user)
-
3
sign_in @admin
-
3
@privacy = create(:privacy_and_legal_policy)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@privacy.title)
-
1
expect(response.body).to include(@privacy.content)
-
1
expect(response.body).to include(@privacy.status.to_s)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @privacy.id }
-
1
expect(response).to render_template(:show)
-
end
-
-
1
it 'displays the page title and content' do
-
1
get :show, params: { id: @privacy.id }
-
1
expect(response.body).to include(@privacy.title)
-
1
expect(response.body).to include(@privacy.content)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ProductContentsController, type: :controller do
-
1
render_views
-
-
9
let(:admin_user) { create(:admin_user) }
-
9
let(:catalogue) { create(:catalogue, product_image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))) }
-
9
let(:product_content) { create(:product_content, catalogue: catalogue) }
-
9
let!(:size_and_capacity) { create(:size_and_capacity, product_content: product_content) }
-
9
let!(:shipping_detail) { create(:shipping_detail, product_content: product_content) }
-
9
let!(:image_urls) { create(:image_url, product_content: product_content) }
-
9
let!(:feature_bullets) { create(:feature_bullet, product_content: product_content) }
-
9
let!(:special_features) { create(:special_feature, product_content: product_content) }
-
-
1
before do
-
8
sign_in admin_user
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
get :index
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:index)
-
end
-
-
1
it 'index displays product content details in response body' do
-
1
get :index
-
-
1
expect(response.body).to include(product_content.gtin)
-
1
expect(response.body).to include(product_content.brand_name)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: product_content.id }
-
1
expect(response).to be_successful
-
end
-
-
1
it 'displays product content details in response body' do
-
1
get :show, params: { id: product_content.id }
-
-
1
expect(response.body).to include(product_content.gtin)
-
1
expect(response.body).to include(product_content.brand_name)
-
1
expect(response.body).to include(size_and_capacity.size.to_s)
-
1
expect(response.body).to include(shipping_detail.shipping_length.to_s)
-
end
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe 'POST #create' do
-
-
1
context 'with invalid params' do
-
3
let(:invalid_attributes) { {retail_price: 123} }
-
-
1
it 'returns a success response (renders the new template)' do
-
1
post :create, params: { product_content: invalid_attributes }
-
1
expect(response).to render_template(:new)
-
end
-
-
1
it 'displays flash errors' do
-
1
post :create, params: { product_content: invalid_attributes }
-
1
expect(flash[:main_model_errors]).not_to be_nil
-
1
expect(flash[:image_urls_errors]).to include("Image URLs: At least one Image Url must be present")
-
1
expect(flash[:feature_bullets_errors]).to include("Feature Bullets: At least one Feature Bullet must be present")
-
end
-
end
-
end
-
-
1
describe 'PUT #update' do
-
-
1
context 'with invalid params' do
-
2
let(:invalid_attributes) { {retail_price: nil, image_urls_attributes: {id: nil, url: nil}, feature_bullets_attributes: {id: nil, value: nil} } }
-
1
it 'returns a success response (renders the edit template)' do
-
1
put :update, params: { id: product_content.id, product_content: invalid_attributes }
-
1
expect(response).to render_template(:edit)
-
1
expect(flash[:main_model_errors]).to eq("Image urls url can't be blank, Image urls url should start with 'https://' or 'www.', Feature bullets value can't be blank, Retail price can't be blank")
-
end
-
end
-
end
-
-
# describe 'DELETE #destroy' do
-
# # it 'destroys the requested product content' do
-
# # expect {
-
# # delete :destroy, params: { id: product_content.id }
-
# # }.to change(BxBlockCatalogue::ProductContent, :count).by(-1)
-
# # end
-
-
# # it 'redirects to the product content list' do
-
# # delete :destroy, params: { id: product_content.id }
-
# # expect(response).to redirect_to(admin_product_path(product_content.catalogue))
-
# # end
-
# end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ProductVariantGroupsController, type: :controller do
-
1
render_views
-
7
let(:admin_user) { create(:admin_user) }
-
6
let(:catalogue) { create(:catalogue) }
-
5
let(:product_variant_group) { create(:product_variant_group, catalogue: catalogue) }
-
-
1
before do
-
6
sign_in admin_user
-
end
-
-
1
describe 'GET #new' do
-
1
it 'returns a success new response' do
-
1
get :new
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'returns a success edit response' do
-
1
get :edit, params: { id: product_variant_group.id }
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success show response' do
-
1
get :show, params: { id: product_variant_group.id }
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success index response' do
-
1
@product_variant_groups = create_list(:product_variant_group,2, catalogue: catalogue)
-
1
get :index
-
1
expect(response).to be_successful
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@product_variant_groups.first.product_sku)
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
it 'updates the product_variant_group attributes' do
-
1
new_sku = 'New SKU'
-
1
new_description = 'New Description'
-
1
new_price = 99.99
-
1
new_title = 'New Title'
-
-
1
patch :update, params: {
-
id: product_variant_group.id,
-
product_variant_group: {
-
product_sku: new_sku,
-
product_description: new_description,
-
price: new_price,
-
product_title: new_title
-
}
-
}
-
-
1
product_variant_group.reload
-
-
1
expect(product_variant_group.product_sku).to eq(new_sku)
-
1
expect(product_variant_group.product_description).to eq(new_description)
-
1
expect(product_variant_group.price.to_s).to eq(new_price.to_s)
-
1
expect(product_variant_group.product_title).to eq(new_title)
-
end
-
-
1
it 'redirects to the catalogue page after update' do
-
1
patch :update, params: { id: product_variant_group.id, product_variant_group: {} }
-
1
expect(response).to redirect_to(admin_product_path(product_variant_group.catalogue))
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::RestrictedBrandRequestsController, type: :controller do
-
1
render_views
-
-
1
before do
-
5
@admin = FactoryBot.create(:admin_user)
-
5
sign_in @admin
-
5
@brand = create(:brand)
-
5
@account = FactoryBot.create(:account, user_type: "seller")
-
5
@restricted_brands = create_list(:restricted_brand, 2, brand: @brand, seller: @account)
-
5
@approved = "No"
-
5
@dow_doc = "Download Document"
-
5
@brand_id = "Brand ##{@brand.id}"
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@brand_id)
-
1
expect(response.body).to include(@approved)
-
1
expect(response.body).to include(@dow_doc)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by brand' do
-
1
get :index, params: { q: { brand_id_eq: @brand.id } }
-
1
expect(response.body).to include(@brand_id)
-
end
-
-
1
it 'filters by approved' do
-
1
get :index, params: { q: { approved_eq: @restricted_brands.first.approved } }
-
1
expect(response.body).to include(@approved)
-
end
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @restricted_brands.first.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(@brand.id.to_s)
-
1
expect(response.body).to include(@approved)
-
1
expect(response.body).to include(@dow_doc)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::ReviewsController, type: :controller do
-
1
render_views
-
14
let!(:admin_user) { create(:admin_user) }
-
14
let!(:account) { create(:account, user_type: 'buyer') }
-
14
let!(:seller) { create(:account, user_type: 'seller') }
-
14
let!(:catalogue) { create(:catalogue, seller: seller) }
-
14
let!(:img_name) {"Sample.jpg"}
-
14
let!(:review) { create(:review, account_id: seller.id, reviewer_id: account.id, review_images: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", img_name))]) }
-
14
let!(:review_2) { create(:review) }
-
1
let(:valid_attributes) do
-
{
-
3
title: "recipe is nice",
-
description: "dummy description",
-
rating: 5,
-
catalogue_id: catalogue.id,
-
reviewer_id: account.id,
-
review_type: 'product',
-
account_id: seller.id,
-
review_images: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", img_name))]
-
}
-
end
-
-
1
before do
-
13
sign_in admin_user
-
end
-
-
1
describe "Get#index" do
-
1
it "listing review and ratings" do
-
1
get :index
-
1
expect(response).to have_http_status(200)
-
end
-
end
-
-
1
describe "Get#show" do
-
1
it "show review and rating" do
-
1
get :show, params: {id: review.id}
-
1
expect(response).to have_http_status(200)
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(img_name)
-
1
expect(response.body).to include(review.account_id.to_s)
-
end
-
-
1
it "show no seller review" do
-
1
get :show, params: {id: review_2.id}
-
1
expect(response).to have_http_status(200)
-
1
expect(response.body).to include("No seller added")
-
end
-
end
-
-
1
describe "GET #edit" do
-
1
it "renders the edit template" do
-
1
get :edit, params: { id: review.id }
-
1
expect(response).to have_http_status(200)
-
1
expect(response).to render_template(:edit)
-
1
expect(response.body).to include(img_name)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe "NEW#review_and_rating" do
-
1
it 'new review and ratings' do
-
1
post :new, params: { review: valid_attributes}
-
1
expect(response).to have_http_status :success
-
end
-
end
-
-
1
describe "Create#Create Review and Rating" do
-
1
it "should create review and ratings" do
-
1
post :create, params: {review: valid_attributes}
-
1
expect(response).to have_http_status(302)
-
end
-
end
-
-
1
describe "Update#Update Review and Rating" do
-
1
it "should update review and ratings" do
-
1
patch :update, params: {review: valid_attributes, id: review.id}
-
1
expect(response).to have_http_status(302)
-
end
-
end
-
-
1
describe "INDEX#filters" do
-
1
it "filters by comment" do
-
1
get :index, params: { filter: { title: review.title } }
-
1
expect(response).to have_http_status(:success)
-
end
-
-
1
it "filters by rating" do
-
1
get :index, params: { filter: { rating: review.rating } }
-
1
expect(response).to have_http_status(:success)
-
end
-
-
1
it "filters by recipe" do
-
1
get :index, params: { filter: { catalogue: review.catalogue_id } }
-
1
expect(response).to have_http_status(:success)
-
end
-
-
1
it "filters by account" do
-
1
get :index, params: { filter: { account: review.account_id } }
-
1
expect(response).to have_http_status(:success)
-
end
-
end
-
-
1
describe 'CSV Export' do
-
1
it 'returns CSV data' do
-
# get :index, format: :csv
-
# expect(response).to have_http_status(:success)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SalesReportController, type: :controller do
-
1
render_views
-
5
let(:admin_user) { create(:admin_user) }
-
5
let(:report_data) { [{ key: 'value' }] }
-
-
1
before do
-
4
sign_in admin_user
-
4
allow(BxBlockSalesreporting::SalesReportService).to receive(:new).and_return(double(call: report_data))
-
end
-
-
1
describe 'GET #index' do
-
1
it 'renders the sales report page' do
-
1
get :index
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.content_type).to eq('text/html; charset=utf-8')
-
1
expect(response.body).to include('Sales Performance Report')
-
end
-
end
-
-
1
describe 'POST #generate_report' do
-
1
let(:start_date) { Date.today.beginning_of_day }
-
1
let(:end_date) { Date.today.end_of_day }
-
-
1
context 'when generating a JSON report' do
-
1
it 'daily returns the report in JSON format' do
-
1
post :generate_report, params: { period: 'daily', report_type: 'json', category_id: 1, format: :json }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)).to eq(report_data.as_json)
-
end
-
-
1
it 'custom returns the report in xml format' do
-
1
post :generate_report, params: { period: 'custom', report_type: 'xml', category_id: 1, format: :xml, start_date: Date.today.beginning_of_day, end_date: Date.today.end_of_day }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.content_type).to eq('application/xml')
-
1
expect(Hash.from_xml(response.body)).to eq('objects' => report_data.as_json)
-
end
-
-
1
it 'custom returns the report in xml format' do
-
1
post :generate_report, params: { period: 'custom', report_type: 'xml', category_id: 1, format: :xml, start_date: Date.today.beginning_of_day, end_date: Date.today.end_of_day }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.content_type).to eq('application/xml')
-
1
expect(Hash.from_xml(response.body)).to eq('objects' => report_data.as_json)
-
end
-
end
-
-
end
-
end
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SellerAccountsController, type: :controller do
-
1
render_views
-
-
1
before do
-
15
@admin = FactoryBot.create(:admin_user)
-
15
sign_in @admin
-
15
@account = create(:account, user_type: 'seller')
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response).to have_http_status(200)
-
1
expect(response.body).to include(@account.email)
-
1
expect(response.body).to include(@account.first_name)
-
1
expect(response.body).to include(@account.last_name)
-
1
expect(response.body).to include(@account.user_type)
-
1
expect(response.body).to include(@account.full_phone_number)
-
1
expect(response.body).to include(@account.activated.to_s)
-
1
expect(response.body).to include(@account.created_at.strftime('%B %d, %Y %H:%M'))
-
1
expect(response.body).to include(@account.updated_at.strftime('%B %d, %Y %H:%M'))
-
1
expect(response.body).to include(@account.language)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by first name' do
-
1
get :index, params: { q: { first_name_cont: @account.first_name } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by last name' do
-
1
get :index, params: { q: { last_name_cont: @account.last_name } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by full phone number' do
-
1
get :index, params: { q: { full_phone_number_cont: @account.full_phone_number } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by email' do
-
1
get :index, params: { q: { email_cont: @account.email } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by language' do
-
1
get :index, params: { q: { language_eq: @account.language } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by activated' do
-
1
get :index, params: { q: { activated_eq: @account.activated } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by created date range' do
-
1
get :index, params: { q: { created_at_gteq: @account.created_at.strftime("%Y-%m-%d 00:00:00"), created_at_lteq: @account.created_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
-
1
it 'filters by updated date range' do
-
1
get :index, params: { q: { updated_at_gteq: @account.updated_at.strftime("%Y-%m-%d 00:00:00"), updated_at_lteq: @account.updated_at.strftime("%Y-%m-%d 23:59:59") } }
-
1
expect(assigns(:seller_accounts)).to include(@account)
-
end
-
end
-
end
-
-
1
describe 'GET show' do
-
# let(:account) { create(:account) }
-
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @account.id }
-
1
expect(response).to render_template(:show)
-
end
-
-
1
it 'assigns the requested account to @account' do
-
1
get :show, params: { id: @account.id }
-
1
expect(assigns(:seller_account)).to eq(@account)
-
end
-
-
1
it 'displays seller documents in the panel' do
-
1
seller_document = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf"))], account: @account)
-
1
get :show, params: { id: @account.id }
-
1
expect(assigns(:seller_account).seller_documents.pluck(:document_type)).to include(seller_document.document_type)
-
1
expect(assigns(:seller_account).seller_documents.pluck(:document_name)).to include(seller_document.document_name)
-
1
expect(assigns(:seller_account).seller_documents.pluck(:approved)).to include(seller_document.approved)
-
1
expect(assigns(:seller_account).seller_documents.pluck(:rejected)).to include(seller_document.rejected)
-
end
-
-
end
-
-
1
describe 'DELETE destroy' do
-
1
context 'when seller account has associated records' do
-
1
before do
-
1
@brand = FactoryBot.create(:brand, account: @account)
-
1
@catalogue = FactoryBot.create(:catalogue, brand: @brand)
-
end
-
-
1
it 'does not delete the seller account and sets a flash alert' do
-
1
expect {
-
1
delete :destroy, params: { id: @account.id }
-
}.not_to change(AccountBlock::Account, :count)
-
1
expect(flash[:alert]).to eq("Cannot delete seller account. Please delete associated products and brands.")
-
1
expect(response).to redirect_to(admin_seller_accounts_path)
-
end
-
end
-
-
1
context 'when seller account has no associated records' do
-
1
it 'deletes the seller account and sets a flash notice' do
-
1
expect {
-
1
delete :destroy, params: { id: @account.id }
-
}.to change(AccountBlock::Account, :count).by(-1)
-
1
expect(flash[:notice]).to eq("Seller account successfully deleted.")
-
1
expect(response).to redirect_to(admin_seller_accounts_path)
-
end
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SellerDocumentsController, type: :controller do
-
1
render_views
-
1
before do
-
9
@admin = FactoryBot.create(:admin_user)
-
9
@seller = FactoryBot.create(:account, user_type: 'seller')
-
9
sign_in @admin
-
9
doc_name = "document.pdf"
-
9
@seller_document = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", doc_name))], account: @seller)
-
9
@seller_documents = AccountBlock::SellerDocument.all
-
9
@seller2 = FactoryBot.create(:account, user_type: 'seller')
-
9
@seller_document1 = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", doc_name))], account: @seller2)
-
9
@seller_document2 = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", doc_name))], account: @seller2, approved: true)
-
9
@seller_document3 = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", doc_name))], account: @seller2, approved: true)
-
9
@seller_document4 = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", doc_name))], account: @seller2, approved: true)
-
9
@seller_document5 = create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", doc_name))], account: @seller2, approved: true)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
end
-
-
1
it 'assigns all seller documents to @seller_documents' do
-
1
get :index
-
1
expect(assigns(:seller_documents)).to match_array(@seller_documents)
-
end
-
end
-
-
1
describe 'GET show' do
-
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @seller_document.id }
-
1
expect(response).to render_template(:show)
-
end
-
-
1
it 'assigns the requested seller document to @seller_document' do
-
1
get :show, params: { id: @seller_document.id }
-
1
expect(assigns(:seller_document)).to eq(@seller_document)
-
end
-
end
-
-
1
describe 'POST update' do
-
-
1
it 'updates the seller document with approved status' do
-
1
post :update, params: { id: @seller_document1.id, seller_document: { approved: true } }
-
1
@seller_document1.reload
-
1
expect(@seller_document1.approved).to eq(true)
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
-
1
it 'updates the seller document with rejected status' do
-
1
post :update, params: { id: @seller_document.id, seller_document: { rejected: true, approved: false } }
-
1
@seller_document.reload
-
1
expect(@seller_document.rejected).to eq(true)
-
1
expect(@seller_document.approved).to eq(false)
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
-
1
it 'updates the seller document with reason for rejection' do
-
1
post :update, params: { id: @seller_document.id, seller_document: { reason_for_rejection: 'Invalid document' } }
-
1
@seller_document.reload
-
1
expect(@seller_document.reason_for_rejection).to eq('Invalid document')
-
end
-
-
1
describe 'POST update_approved' do
-
1
it 'updates the seller document and redirects to admin_account_path' do
-
1
post :update, params: { id: @seller_document.id, seller_document: { rejected: '1' } }
-
1
expect(response).to redirect_to(admin_seller_account_path(@seller_document.account))
-
1
expect(flash[:notice]).to eq('Document updated successfully.')
-
1
expect(@seller_document.reload.approved).to eq(false)
-
end
-
-
1
it 'updates the seller document and renders the edit template' do
-
1
post :update, params: { id: @seller_document.id, seller_document: { rejected: true, approved: true} }
-
1
expect(flash[:error]).to eq("Only one status can be selected: either 'approved' or 'rejected', but not both.")
-
end
-
end
-
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SellerFooterPagesController, type: :controller do
-
1
render_views
-
-
1
before do
-
4
@admin = FactoryBot.create(:admin_user)
-
4
sign_in @admin
-
4
@seller_static_pages = create_list(:seller_static_page, 2, section: 'footer')
-
end
-
-
1
describe 'GET index footer' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@seller_static_pages.first.title)
-
1
expect(response.body).to include(@seller_static_pages.first.content)
-
1
expect(response.body).to include(@seller_static_pages.first.section)
-
1
expect(response.body).to include('No')
-
end
-
end
-
-
1
describe 'GET show footer' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @seller_static_pages.first.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:seller_footer_pages)).to eq(@seller_static_pages.first)
-
end
-
-
1
it 'renders fulfillment by partner page' do
-
1
get :show, params: { id: @seller_static_pages.last.id }
-
-
1
expect(assigns(:seller_footer_pages).title).to eq(@seller_static_pages.last.title)
-
end
-
end
-
-
1
describe 'GET edit footer' do
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: @seller_static_pages.last.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SellerHeaderPagesController, type: :controller do
-
1
render_views
-
-
1
before do
-
3
@admin = FactoryBot.create(:admin_user)
-
3
sign_in @admin
-
3
@seller_static_pages = create_list(:seller_static_page, 2)
-
end
-
-
1
describe 'GET index header' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@seller_static_pages.first.title)
-
1
expect(response.body).to include(@seller_static_pages.first.content)
-
1
expect(response.body).to include(@seller_static_pages.first.section)
-
1
expect(response.body).to include('No')
-
end
-
end
-
-
1
describe 'GET show header' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @seller_static_pages.last.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:seller_header_pages)).to eq(@seller_static_pages.last)
-
end
-
end
-
-
1
describe 'GET edit header' do
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: @seller_static_pages.last.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SocialPlatformsController, type: :controller do
-
1
render_views
-
-
1
before do
-
3
@admin = FactoryBot.create(:admin_user)
-
3
sign_in @admin
-
3
@social_platform = create(:social_platform)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@social_platform.social_media)
-
1
expect(response.body).to include(@social_platform.social_media_url)
-
end
-
end
-
-
1
describe 'GET show' do
-
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @social_platform.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:social_platforms)).to eq(@social_platform)
-
1
expect(Rails.application.routes.url_helpers.rails_blob_path(assigns(:social_platforms).social_icon, only_path: true)).to include(Rails.application.routes.url_helpers.rails_blob_path(@social_platform.social_icon, only_path: true))
-
end
-
-
end
-
-
1
describe "GET #edit" do
-
1
it "returns a successful response" do
-
1
get :edit, params: { id: @social_platform.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::FooterStaticPagesController, type: :controller do
-
1
render_views
-
-
1
before do
-
3
@admin = FactoryBot.create(:admin_user)
-
3
sign_in @admin
-
3
@static_pages = create_list(:static_page, 2)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@static_pages.first.title)
-
1
expect(response.body).to include(@static_pages.first.content)
-
end
-
end
-
-
1
describe 'GET show' do
-
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @static_pages.last.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:footer_static_pages)).to eq(@static_pages.last)
-
end
-
-
end
-
-
1
describe 'GET edit' do
-
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: @static_pages.last.id }
-
1
expect(response).to render_template(:edit)
-
end
-
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::StoresController, type: :controller do
-
1
render_views
-
-
1
before do
-
10
@admin = FactoryBot.create(:admin_user)
-
10
sign_in @admin
-
10
@store = create(:store)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
-
1
get :show, params: { id: @store.id }
-
1
expect(response).to render_template(:show)
-
1
expect(response.body).to include(@store.store_name)
-
1
expect(response.body).to include(@store.store_year.to_s)
-
1
expect(response.body).to include(@store.store_url)
-
1
expect(response.body).to include(@store.website_social_url)
-
1
expect(response.body).to include(@store.brand_trade_certificate.filename.to_s) if @store.brand_trade_certificate.attached?
-
1
expect(response.body).to include("Yes")
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'Filters' do
-
1
it 'filters by store_name' do
-
1
get :index, params: { q: { store_name_eq: @store.store_name } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
-
1
it 'filters by store_year' do
-
1
get :index, params: { q: { store_year_eq: @store.store_year } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
-
1
it 'filters by store_url' do
-
1
get :index, params: { q: { store_url_eq: @store.store_url } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
-
1
it 'filters by website_social_url' do
-
1
get :index, params: { q: { website_social_url_eq: @store.website_social_url } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
-
1
it 'filters by approve' do
-
1
get :index, params: { q: { approve_eq: @store.approve } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: { q: { created_at_gteq_datetime: @store.created_at.strftime('%Y-%m-%d 00:00:00'), created_at_lteq_datetime: @store.created_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: { q: { updated_at_gteq_datetime: @store.updated_at.strftime('%Y-%m-%d 00:00:00'), updated_at_lteq_datetime: @store.updated_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:stores)).to include(@store)
-
end
-
end
-
-
# describe 'POST create' do
-
# it 'creates a new store' do
-
# brand = FactoryBot.create(:brand)
-
# post :create, params: { store: { brand_id: brand.id, store_name: 'Test Store', store_year: 2023, store_url: 'http://teststore.com', website_social_url: 'http://social.teststore.com', approve: true } }
-
# expect(response).to have_http_status(:ok)
-
# expect(BxBlockStoreManagement::Store.first.store_name).to eq('Test Store')
-
# end
-
-
# it 'renders errors if creation fails' do
-
# post :create, params: { store: { brand_id: nil, store_name: 'Test Store', store_year: 2023, store_url: 'http://teststore.com', website_social_url: 'http://social.teststore.com', approve: true } }
-
# expect(response).to have_http_status(:unprocessable_entity)
-
# expect(json_response['errors']).to include("Brand must exist")
-
# end
-
# end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SubCategoriesController, type: :controller do
-
1
render_views
-
1
before do
-
7
@admin = FactoryBot.create(:admin_user)
-
7
sign_in @admin
-
7
@category = create(:category)
-
7
@sub_category = create(:sub_category, category: @category)
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template and assigns the sub category' do
-
1
custom_field = create(:custom_field, fieldable: @sub_category)
-
-
-
1
get :show, params: { id: @sub_category.id }
-
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:sub_categories)).to eq(@sub_category)
-
1
expect(assigns(:sub_categories).custom_fields).to include(custom_field)
-
1
expect(assigns(:sub_categories).category).to eq(@category)
-
end
-
end
-
-
1
describe "index page" do
-
1
it "displays a list of subcategories" do
-
1
sub_category2 = create(:sub_category,name: Faker::Lorem.word + Faker::Lorem.word, category: @category)
-
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
expect(response.body).to include(@sub_category.name)
-
1
expect(response.body).to include(sub_category2.name)
-
end
-
end
-
-
1
describe "GET new" do
-
1
it "displays the new sub category form" do
-
1
get :new
-
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe "POST create" do
-
1
it "creates a new subcategory" do
-
1
sub_category_params = { name: "New Subcategory", parent_id: @category.id }
-
-
1
expect {
-
1
post :create, params: { sub_category: sub_category_params }
-
}.to change(BxBlockCategories::SubCategory, :count).by(1)
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(@category))
-
end
-
end
-
-
1
describe "PUT update" do
-
1
it "updates the attributes of a subcategory" do
-
1
updated_name = "Updated Subcategory"
-
-
1
put :update, params: { id: @sub_category.id, sub_category: { name: updated_name, parent_id: @sub_category.category.id } }
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(@sub_category.category))
-
1
expect(@sub_category.reload.name).to eq(updated_name)
-
end
-
-
1
it "invalid updates the attributes of a subcategory" do
-
-
1
put :update, params: { id: @sub_category.id, sub_category: { name: '', parent_id: @sub_category.category.id } }
-
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
1
describe "DELETE destroy" do
-
1
it "deletes a subcategory" do
-
1
expect {
-
1
delete :destroy, params: { id: @sub_category.id }
-
}.to change(BxBlockCategories::SubCategory, :count).by(-1)
-
-
1
expect(response).to have_http_status(:redirect)
-
1
expect(response).to redirect_to(admin_category_path(@sub_category.category))
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SuggestionFeedbacksController, type: :controller do
-
1
render_views
-
4
let(:admin_user) { create(:admin_user) }
-
-
1
before do
-
3
sign_in admin_user
-
3
@suggestion_feedback = create(:suggestion_feedback)
-
end
-
-
1
describe "GET /admin/suggestion_feedbacks" do
-
1
it "displays the suggestion feedbacks index page" do
-
-
1
get :index
-
-
1
expect(response).to have_http_status(200)
-
1
expect(response.body).to include(@suggestion_feedback.email)
-
1
expect(response.body).to include(@suggestion_feedback.first_name)
-
1
expect(response.body).to include(@suggestion_feedback.last_name)
-
1
expect(response.body).to include(@suggestion_feedback.detail_type)
-
end
-
end
-
-
1
describe "GET /admin/suggestion_feedbacks/:id" do
-
1
it "displays the suggestion feedback show page" do
-
-
-
1
get :show , params: { id: @suggestion_feedback.id }
-
-
1
expect(response).to have_http_status(200)
-
1
expect(response.body).to include(@suggestion_feedback.email)
-
1
expect(response.body).to include(@suggestion_feedback.first_name)
-
1
expect(response.body).to include(@suggestion_feedback.last_name)
-
1
expect(response.body).to include(@suggestion_feedback.detail_type)
-
end
-
end
-
-
# describe "POST /admin/suggestion_feedbacks" do
-
# it "creates a new suggestion feedback" do
-
-
# expect {
-
# post :create, params: { suggestion_feedback: {email: "test@gmail.com",first_name: "test",last_name: "user",detail_type: "FeedBack", account_id: @suggestion_feedback.account_id } }
-
# }.to change(AccountBlock::SuggestionFeedback, :count).by(1)
-
-
# expect(response).to have_http_status(302)
-
# expect(response).to redirect_to(admin_suggestion_feedback_path(AccountBlock::SuggestionFeedback.last))
-
# end
-
# end
-
-
1
describe 'GET new' do
-
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SupportDocumentsController, type: :controller do
-
1
render_views
-
-
1
before do
-
4
@admin = FactoryBot.create(:admin_user)
-
4
sign_in @admin
-
4
@support_document = create(:support_document)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@support_document.page_title)
-
1
expect(response.body).to include(@support_document.content)
-
end
-
end
-
-
1
describe 'GET edit' do
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: @support_document.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @support_document.id }
-
1
expect(response).to render_template(:show)
-
end
-
-
1
it 'displays the page title and content' do
-
1
get :show, params: { id: @support_document.id }
-
1
expect(response.body).to include(@support_document.page_title)
-
1
expect(response.body).to include(@support_document.content)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::SupportContactsController, type: :controller do
-
1
render_views
-
-
1
before do
-
3
@admin = FactoryBot.create(:admin_user)
-
3
sign_in @admin
-
3
@supports = create_list(:support, 2)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@supports.first.first_name)
-
1
expect(response.body).to include(@supports.first.last_name)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @supports.last.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:support_contacts)).to eq(@supports.last)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::TermsAndPoliciesController, type: :controller do
-
1
render_views
-
-
1
before do
-
3
@admin = FactoryBot.create(:admin_user)
-
3
sign_in @admin
-
3
@terms_policy = create(:terms_policy)
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response.body).to include(@terms_policy.page_title)
-
1
expect(response.body).to include(@terms_policy.content)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @terms_policy.id }
-
1
expect(response).to render_template(:show)
-
end
-
-
1
it 'displays the page title and content' do
-
1
get :show, params: { id: @terms_policy.id }
-
1
expect(response.body).to include(@terms_policy.page_title)
-
1
expect(response.body).to include(@terms_policy.content)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::TopBannersController, type: :controller do
-
1
render_views
-
-
10
let(:admin_user) { create(:admin_user) }
-
-
1
before do
-
9
BxBlockDashboard::BannerGroup.all.delete_all
-
9
sign_in admin_user
-
9
@banner = BxBlockDashboard::Banner.find_or_create_by(title: "Free shipping on all UAE orders AED 200", button_text: "SHOP NOW",banner_type: "top_banner", button_link: "https://www.url.com", status: true)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'renders the index template' do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'assigns @banners' do
-
1
get :index
-
1
expect(assigns(:top_banners)).to include(@banner)
-
end
-
-
1
context 'with filters' do
-
1
it 'filters by title' do
-
1
get :index, params: { q: { title_cont: @banner.title } }
-
1
expect(assigns(:top_banners)).to include(@banner)
-
end
-
-
1
it 'filters by button_text' do
-
1
get :index, params: { q: { button_text_cont: @banner.button_text } }
-
1
expect(assigns(:top_banners)).to include(@banner)
-
end
-
-
1
it 'filters by button_url' do
-
1
get :index, params: { q: { button_link_cont: @banner.button_link } }
-
1
expect(assigns(:top_banners)).to include(@banner)
-
end
-
-
1
it 'filters by created_at' do
-
1
get :index, params: {
-
q: {
-
created_at_gteq: @banner.created_at.strftime("%Y-%m-%d 00:00:00"),
-
created_at_lteq: @banner.created_at.strftime("%Y-%m-%d 23:59:59")
-
}
-
}
-
1
expect(assigns(:top_banners)).to include(@banner)
-
end
-
-
1
it 'filters by updated_at' do
-
1
get :index, params: {
-
q: {
-
updated_at_gteq: @banner.updated_at.strftime("%Y-%m-%d 00:00:00"),
-
updated_at_lteq: @banner.updated_at.strftime("%Y-%m-%d 23:59:59")
-
}
-
}
-
1
expect(assigns(:top_banners)).to include(@banner)
-
end
-
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'renders the show template' do
-
1
get :show, params: { id: @banner.id }
-
1
expect(response).to render_template(:show)
-
1
expect(assigns(:top_banner)).to eq(@banner)
-
end
-
end
-
-
1
describe 'GET #edit' do
-
1
it 'renders the edit template' do
-
1
get :edit, params: { id: @banner.id }
-
1
expect(response).to render_template(:edit)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::TopBrandsController, type: :controller do
-
1
render_views
-
-
1
before do
-
5
@admin = FactoryBot.create(:admin_user)
-
5
sign_in @admin
-
5
@top_brand = create(:top_brand)
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'POST create with invalid params' do
-
3
let(:invalid_params) { { top_brand: { brand_id: nil, sequence_no: 1 } } }
-
-
1
it 'does not create a new top brand' do
-
2
expect { post :create, params: invalid_params }.not_to change(BxBlockDashboard::TopBrand, :count)
-
end
-
-
1
it '#create renders the new template' do
-
1
post :create, params: invalid_params
-
1
expect(flash[:error]).to include("Brand must exist")
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'PATCH update with invalid params' do
-
-
1
context 'with invalid params' do
-
3
let(:invalid_params) { { id: @top_brand.id, top_brand: { brand_id: nil, sequence_no: -1 } } }
-
-
1
it 'provides error messages in the flash' do
-
1
patch :update, params: invalid_params
-
1
expect(flash[:error]).to include("Sequence no must be greater than or equal to 1")
-
1
expect(response).to render_template(:edit)
-
end
-
-
1
it 'renders the edit template' do
-
1
patch :update, params: invalid_params
-
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::TrendingProductsController, type: :controller do
-
1
render_views
-
-
1
before do
-
2
@admin = FactoryBot.create(:admin_user)
-
2
sign_in @admin
-
2
@seller = create(:account, user_type: 'seller')
-
2
@catalogues = create_list(:catalogue,6, seller: @seller)
-
2
trending_product_selections_attributes = @catalogues.map do |catalogue|
-
12
{ catalogue_id: catalogue.id }
-
end
-
2
@trending_product = create(:trending_product, slider: 'slider_1', trending_product_selections_attributes: trending_product_selections_attributes)
-
2
@params_tp = {slider: 'slider_2', trending_product_selections_attributes: trending_product_selections_attributes}
-
end
-
-
1
describe "GET #show" do
-
1
it "returns http success" do
-
1
get :show, params: { id: @trending_product.id }
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::WarehousesController, type: :controller do
-
-
1
render_views
-
1
before do
-
8
@admin = FactoryBot.create(:admin_user)
-
8
sign_in @admin
-
8
@warehouse1 = FactoryBot.create(:warehouse)
-
end
-
-
2
let(:valid_attributes) { { warehouse_type: "Test type", warehouse_name: "Warehouse name test" } }
-
-
1
describe "index page" do
-
1
it "displays a list of warehouses" do
-
1
warehouse2 = FactoryBot.create(:warehouse, warehouse_type: "Type B", warehouse_name: "Warehouse 2")
-
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
expect(response.body).to include(@warehouse1.warehouse_name)
-
1
expect(response.body).to include(warehouse2.warehouse_name)
-
end
-
-
1
it "filters by warehouse_name" do
-
1
get :index, params: { q: { warehouse_name_eq: @warehouse1.warehouse_name } }
-
1
expect(assigns(:warehouses)).to include(@warehouse1)
-
end
-
-
1
it "filters by warehouse_address" do
-
1
get :index, params: { q: { processing_days_eq: @warehouse1.processing_days } }
-
1
expect(assigns(:warehouses)).to include(@warehouse1)
-
end
-
-
1
it "filters by created_at" do
-
1
get :index, params: { q: { created_at_gteq_datetime: @warehouse1.created_at.strftime('%Y-%m-%d 00:00:00'), created_at_lteq_datetime: @warehouse1.created_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:warehouses)).to include(@warehouse1)
-
end
-
-
1
it "filters by updated_at" do
-
1
get :index, params: { q: { updated_at_gteq_datetime: @warehouse1.updated_at.strftime('%Y-%m-%d 00:00:00'), updated_at_lteq_datetime: @warehouse1.updated_at.strftime('%Y-%m-%d 23:59:59') } }
-
1
expect(assigns(:warehouses)).to include(@warehouse1)
-
end
-
-
end
-
-
1
describe "show page" do
-
1
it "displays the details of a warehouse" do
-
1
get :show, params: {id: @warehouse1.id}
-
1
expect(assigns(:warehouse)).to eq(@warehouse1)
-
end
-
end
-
-
1
describe "GET #new" do
-
1
it "returns a successful response" do
-
1
get :new
-
1
expect(response).to have_http_status(:ok)
-
1
expect(assigns(:warehouse)).to be_a_new(BxBlockCatalogue::Warehouse)
-
end
-
end
-
-
1
describe "POST #create" do
-
1
context "with valid parameters" do
-
1
it "creates a new warehouse" do
-
1
expect {
-
1
post :create, params: { warehouse: valid_attributes }
-
}.to change(BxBlockCatalogue::Warehouse, :count).by(1)
-
1
expect(response).to redirect_to(admin_warehouse_path(BxBlockCatalogue::Warehouse.last))
-
1
expect(flash[:notice]).to eq("Warehouse was successfully created.")
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::WeeklyDealsController, type: :controller do
-
1
render_views
-
-
1
before do
-
2
@admin = FactoryBot.create(:admin_user)
-
2
sign_in @admin
-
2
@deal = FactoryBot.create(:deal)
-
2
@bg_image = fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))
-
weekly_deals_attributes = [
-
2
{ caption: "slider1", discount_percent: 1.0, url: "https://slider1", deal: @deal, bg_image: @bg_image },
-
{ caption: "slider2", discount_percent: 2.0, url: "https://slider2", deal: @deal, bg_image: @bg_image },
-
{ caption: "slider3", discount_percent: 3.0, url: "https://slider3", deal: @deal, bg_image: @bg_image }
-
]
-
-
2
@weekly_homiee_deal_d = create(:weekly_homiee_deal, weekly_deals_attributes: weekly_deals_attributes)
-
-
end
-
-
1
describe "GET #show" do
-
1
it "returns http success" do
-
1
get :show, params: { id: @weekly_homiee_deal_d.weekly_deals.first.id }
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe Admin::WeeklyHomieeDealsController, type: :controller do
-
1
render_views
-
-
1
before do
-
13
@admin = FactoryBot.create(:admin_user)
-
13
sign_in @admin
-
13
@deal = FactoryBot.create(:deal)
-
13
@bg_image = fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))
-
@weekly_deals_attributes = [
-
13
{ caption: "slider1", discount_percent: 1.0, url: "https://slider1", deal: @deal, bg_image: @bg_image },
-
{ caption: "slider2", discount_percent: 2.0, url: "https://slider2", deal: @deal, bg_image: @bg_image },
-
{ caption: "slider3", discount_percent: 3.0, url: "https://slider3", deal: @deal, bg_image: @bg_image }
-
]
-
13
@current_date = Date.current
-
13
@tomorrow_date = Date.tomorrow + 2.days
-
13
@yesterday_date = Date.yesterday
-
-
13
@weekly_homiee_deal = create(:weekly_homiee_deal, weekly_deals_attributes: @weekly_deals_attributes)
-
-
end
-
-
1
describe "GET #show" do
-
1
it "returns http success" do
-
1
get :show, params: { id: @weekly_homiee_deal.id }
-
1
expect(response).to have_http_status(:success)
-
1
expect(response).to render_template(:show)
-
end
-
end
-
-
1
describe 'GET new' do
-
1
it 'renders the new template' do
-
1
get :new
-
1
expect(response).to render_template(:new)
-
end
-
end
-
-
1
describe 'Validations' do
-
1
context 'when validating max_weekly_deals' do
-
-
1
it 'should add error message if weekly_deals size is not 3' do
-
1
@weekly_homiee_deal.weekly_deals = []
-
1
@weekly_homiee_deal.save
-
1
expect(@weekly_homiee_deal.errors[:weekly_deals]).to include("must be exactly 3 and cannot be blank")
-
end
-
end
-
-
1
context 'when validating end_date_must_be_today_or_later_and_present' do
-
1
it 'should add error message if end_time is in the past' do
-
1
@weekly_homiee_deal.end_time = @yesterday_date
-
1
@weekly_homiee_deal.save
-
1
expect(@weekly_homiee_deal.errors[:end_date]).to include("must be today or after start time")
-
end
-
end
-
-
1
context 'when validating start_time_must_be_today_or_later_and_present' do
-
1
it 'should add error message if start_time is in the past' do
-
1
@weekly_homiee_deal.start_time = @yesterday_date
-
1
@weekly_homiee_deal.save
-
1
expect(@weekly_homiee_deal.errors[:start_time]).to include("must be today or later")
-
end
-
end
-
end
-
-
1
describe "GET #index" do
-
1
it "returns http success" do
-
1
get :index
-
1
expect(response).to have_http_status(:success)
-
end
-
-
1
it "renders the index template" do
-
1
get :index
-
1
expect(response).to render_template(:index)
-
end
-
-
1
it "filters by weekly_deals" do
-
1
get :index, params: { q: { weekly_deals_id_eq: @weekly_homiee_deal.weekly_deals.first.id } }
-
1
expect(assigns(:weekly_homiee_deals)).to include(@weekly_homiee_deal)
-
end
-
-
1
it "filters by start_time" do
-
1
get :index, params: { q: { start_time_gteq: @current_date } }
-
1
expect(assigns(:weekly_homiee_deals)).to include(@weekly_homiee_deal)
-
end
-
-
1
it "filters by end_time" do
-
1
get :index, params: { q: { end_time_lteq: @tomorrow_date } }
-
1
expect(assigns(:weekly_homiee_deals)).to include(@weekly_homiee_deal)
-
end
-
-
1
it "filters by status" do
-
1
get :index, params: { q: { status_eq: 'No' } }
-
1
expect(assigns(:weekly_homiee_deals)).to include(@weekly_homiee_deal)
-
end
-
-
1
it "filters by created_at" do
-
1
get :index, params: { q: { created_at_gteq: @current_date } }
-
1
expect(assigns(:weekly_homiee_deals)).to include(@weekly_homiee_deal)
-
end
-
-
1
it "filters by updated_at" do
-
1
get :index, params: { q: { updated_at_gteq: @current_date } }
-
1
expect(assigns(:weekly_homiee_deals)).to include(@weekly_homiee_deal)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::AccountsController, type: :controller do
-
2
let(:new_pass) {"User@321"}
-
19
let(:acc_pass) {"User@123"}
-
1
let(:new_email) {"new_test@email.co"}
-
4
let(:update_name) {'Updated Name'}
-
19
let(:valid_account) { create(:account, password: acc_pass, user_type: 'seller') }
-
2
let(:buyer) { create(:account, password: acc_pass, user_type: 'buyer') }
-
2
let(:catalogue) { create(:catalogue) }
-
1
let(:review) { create(:review, 3, reviewer_id: buyer.id, catalogue: catalogue, account_id: valid_account.id, rating: rating, review_type: 'seller', is_approved: true) }
-
8
let(:token) { BuilderJsonWebToken.encode(valid_account.id) }
-
4
let(:non_existing_id) { 999 }
-
4
let(:not_found) {'Account not found'}
-
3
let(:email_invalid) {'Email invalid'}
-
1
let(:doc_valid_attributes) {
-
{
-
3
document_type: "Trading License or Commercial Registration",
-
document_name: "License",
-
document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf"))],
-
approved: true
-
}
-
}
-
-
1
describe 'POST #create' do
-
-
1
let(:valid_account_params) do
-
{
-
7
first_name: Faker::Name.first_name,
-
last_name: Faker::Name.last_name,
-
company_or_store_name: Faker::Company.name,
-
email: Faker::Internet.email,
-
full_phone_number: "9190 + #{rand(100000...999999)}",
-
password: 'Pass@123',
-
confirm_password: 'Pass@123'
-
}
-
end
-
-
1
let(:invalid_account_params) do
-
2
valid_account_params.merge({confirm_password: '',full_phone_number: '',password: ''})
-
end
-
-
1
context 'with valid parameters' do
-
1
it 'creates a new seller account' do
-
1
post :create, params: {
-
data: {
-
user_type: 'seller',
-
attributes: valid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)['message']).to include("Seller and Buyer accounts created successfully")
-
1
expect(JSON.parse(response.body)).to have_key("seller")
-
1
expect(JSON.parse(response.body)).to have_key("buyer")
-
1
expect(JSON.parse(response.body)).to have_key("token")
-
1
expect(JSON.parse(response.body)['seller']['data']['attributes']['email']).to eq(BxBlockActivitylog::ActivityLog.find_by(user_email: valid_account_params[:email]).user_email)
-
end
-
-
1
it 'creates a new seller account with buyer error' do
-
1
buyer_account = create(:account, user_type: 'buyer', activated: true)
-
1
valid_account_params[:email] = buyer_account.email
-
1
post :create, params: {
-
data: {
-
user_type: 'seller',
-
attributes: valid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)['message']).to include("Seller account created, but buyer account already exists")
-
1
expect(JSON.parse(response.body)).to have_key("seller")
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq("Email has already been taken")
-
1
expect(JSON.parse(response.body)).to have_key("token")
-
end
-
-
1
it 'creates a new buyer account' do
-
1
post :create, params: {
-
data: {
-
user_type: 'buyer',
-
attributes: valid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'with invalid parameters' do
-
1
it 'returns errors for invalid attributes' do
-
1
post :create, params: {
-
data: {
-
user_type: 'seller',
-
attributes: invalid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
body = JSON.parse(response.body)
-
1
expect(body['errors'][0]).to include("Password can't be blank")
-
end
-
-
1
it 'returns errors for invalid match password' do
-
1
invalid_account_params[:confirm_password] = "asd123hfgk"
-
1
invalid_account_params[:password] = "asd1hfgk"
-
1
post :create, params: {
-
data: {
-
user_type: 'seller',
-
attributes: invalid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
body = JSON.parse(response.body)
-
1
expect(body['errors'][0]['accounts']).to include("Password and confirm password should be the same")
-
end
-
end
-
-
1
context 'with existing account email' do
-
2
let!(:existing_account) { create(:account, email: valid_account_params[:email], user_type: 'buyer', activated: true) }
-
-
1
it 'returns an error' do
-
1
post :create, params: {
-
data: {
-
user_type: 'buyer',
-
attributes: valid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
body = JSON.parse(response.body)
-
1
expect(body['errors'][0]).to eq("Email has already been taken")
-
end
-
end
-
-
1
context 'with unknown user type' do
-
1
it 'returns an error' do
-
1
post :create, params: {
-
data: {
-
user_type: 'unknown',
-
attributes: valid_account_params
-
}
-
}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
body = JSON.parse(response.body)
-
1
expect(body['errors'][0]['accounts']).to eq('Unknown user type')
-
end
-
end
-
end
-
-
1
describe 'GET #account_activation' do
-
-
1
context 'when a valid token is provided' do
-
3
let(:account) { FactoryBot.create(:account, user_type: 'seller', activated: false) }
-
3
let(:valid_token) { BuilderJsonWebToken.encode(account.id) }
-
-
1
before do
-
2
@buyer_account = FactoryBot.create(:account, user_type: 'buyer', email: account.email, activated: false)
-
2
get :account_activation, params: { token: valid_token }
-
2
account.reload
-
2
@buyer_account.reload
-
end
-
-
1
it 'activates the account' do
-
1
expect(account.activated).to be true
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['meta']).to have_key('token')
-
1
expect(@buyer_account.activated).to be true
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
-
1
it 'invalid activation link' do
-
1
get :account_activation, params: { token: valid_token }
-
1
body = JSON.parse(response.body)
-
1
expect(body['errors']).to eq('Invalid activation link. Please try again or contact support.')
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
end
-
-
1
context 'when an invalid token is provided' do
-
1
it 'returns an error for invalid token' do
-
1
get :account_activation, params: { }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
body = JSON.parse(response.body)
-
1
expect(body['errors']).to eq('Invalid token')
-
end
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns the account details' do
-
1
get :show, params: { id: valid_account.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(valid_account.full_name)
-
1
expect(response.body).to include(valid_account.email)
-
end
-
-
1
it 'returns an error if the account is not found when show' do
-
1
get :show, params: { id: non_existing_id }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response.body).to include(not_found)
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
4
let(:valid_attributes) { { full_name: update_name, email: valid_account.email } }
-
2
let(:invalid_attributes) { { email: 'invalid_email' } }
-
-
1
it 'updates the account with valid attributes' do
-
1
patch :update, params: { id: valid_account.id, data: { attributes: valid_attributes } }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to include("Profile updated successfully!")
-
1
expect(valid_account.reload.full_name).to eq(update_name)
-
end
-
-
1
it 'updates the account with valid full_name' do
-
1
patch :update, params: { id: valid_account.id, data: { attributes: valid_attributes.except(:email) } }
-
1
expect(JSON.parse(response.body)['message']).to include("Seller name updated successfully!")
-
end
-
-
1
it 'updates the account with valid company_or_store_name' do
-
1
patch :update, params: { id: valid_account.id, data: { attributes: { company_or_store_name: 'store1name' } } }
-
1
expect(JSON.parse(response.body)['message']).to include("Store name updated successfully!")
-
end
-
-
1
it 'updates the account with valid first name' do
-
1
patch :update, params: { id: valid_account.id, data: { attributes: { first_name: 'first1name' } } }
-
1
expect(JSON.parse(response.body)['message']).to include("First name updated successfully!")
-
end
-
-
1
it 'updates the account with valid password' do
-
1
patch :update, params: { id: valid_account.id, data: { attributes: {current_password: acc_pass,new_password: new_pass } } }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(BCrypt::Password.new(valid_account.reload.password_digest)).to eq(new_pass)
-
1
expect(JSON.parse(response.body)['message']).to include("Password updated successfully!")
-
end
-
-
1
it 'returns an error if the account is not found when update' do
-
1
patch :update, params: { id: non_existing_id, data: { attributes: valid_attributes } }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response.body).to include(not_found)
-
end
-
-
1
it 'returns an error if the attributes are invalid' do
-
1
patch :update, params: { id: valid_account.id, data: { attributes: invalid_attributes } }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include(email_invalid)
-
end
-
-
1
it 'returns an error if the new password and confirm password do not match' do
-
1
attributes = { current_password: 'password123', new_password: 'password456' }
-
1
patch :update, params: { id: valid_account.id, data: { attributes: attributes } }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include('Incorrect current password')
-
end
-
-
1
it 'returns an error if the email already exists' do
-
1
existing_account = create(:account, email: 'existing@example.com')
-
1
attributes = { email: 'existing@example.com' }
-
1
patch :update, params: { id: valid_account.id, data: { attributes: attributes } }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include(email_invalid)
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'deletes the account' do
-
1
delete :destroy, params: { id: valid_account.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include('Account deleted successfully')
-
2
expect { AccountBlock::Account.find(valid_account.id) }.to raise_error(ActiveRecord::RecordNotFound)
-
end
-
-
1
it 'returns an error if the account is not found when destroy' do
-
1
delete :destroy, params: { id: non_existing_id }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response.body).to include(not_found)
-
end
-
end
-
-
1
describe 'POST resend_email' do
-
-
1
before do
-
2
post :resend_email, params: { token: token }
-
end
-
-
1
it 'resends the activation email' do
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a success message' do
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['message']).to eq('Activation email has been resent')
-
end
-
end
-
-
1
describe 'GET logged_user' do
-
1
context 'when the account exists' do
-
1
it 'returns the logged user account details' do
-
1
get :logged_user, params: { token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to eq(AccountBlock::AccountSerializer.new(valid_account).serializable_hash.to_json)
-
end
-
end
-
-
1
it 'returns an no doc status' do
-
1
review = create(:review, reviewer_id: buyer.id, catalogue: catalogue, account_id: valid_account.id, rating: 4, review_type: 'seller', is_approved: true)
-
1
get :logged_user, params: { token: token}
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['document_status']).to eq("No documents uploaded")
-
1
expect(json_response['data']['attributes']['seller_rating']['total_reviews']).to eq(1)
-
1
expect(json_response['data']['attributes']['first_time_login']).to eq(false)
-
end
-
-
1
it 'returns an approved doc status approved' do
-
1
doc = AccountBlock::SellerDocument.create!(doc_valid_attributes.merge(account_id: valid_account.id))
-
1
get :logged_user, params: { token: token}
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['document_status']).to eq("Your document has been verified")
-
end
-
-
1
it 'returns an approved doc status inprogress' do
-
1
doc_valid_attributes[:approved] = false
-
1
doc_valid_attributes[:rejected] = false
-
1
doc2 = AccountBlock::SellerDocument.create!(doc_valid_attributes.merge(account_id: valid_account.id))
-
1
get :logged_user, params: { token: token}
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['document_status']).to eq("Your Document verification is in progress")
-
end
-
-
1
it 'returns an approved doc status rejected' do
-
1
doc_valid_attributes[:document_type] = "Residence visa for non-nationals"
-
1
doc_valid_attributes[:approved] = false
-
1
doc_valid_attributes[:rejected] = true
-
1
doc1 = AccountBlock::SellerDocument.create!(doc_valid_attributes.merge(account_id: valid_account.id))
-
1
get :logged_user, params: { token: token}
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['document_status']).to eq("Rejected: License")
-
end
-
end
-
-
1
describe "POST upload_image" do
-
1
context "with image file attaches" do
-
3
let(:account) { FactoryBot.create(:account, activated: true) }
-
3
let(:valid_token) { BuilderJsonWebToken.encode(account.id) }
-
-
1
it "attaches the profile picture to the account" do
-
1
image_data = fixture_file_upload('files/Sample.jpg', 'image/jpeg')
-
1
post :upload_image, params: { token: valid_token, profile_picture: image_data }
-
1
expect(account.reload.profile_picture).to be_attached
-
end
-
-
1
it "should remove attached the profile picture from account when no image provided" do
-
1
post :upload_image, params: { token: valid_token }
-
1
expect(account.reload.profile_picture).not_to be_attached
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::SellerDocumentsController, type: :request do
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@seller = create(:account, user_type: "seller")
-
1
@token_s = BuilderJsonWebToken.encode(@seller.id, token_type: 'login')
-
end
-
-
1
let(:valid_attributes) {
-
{
-
4
document_type: "Trading License or Commercial Registration",
-
document_name: "License",
-
document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf"))]
-
}
-
}
-
-
1
let(:invalid_attributes) {
-
{
-
1
document_type: "Trading License or Commercial Registration",
-
document_name: "License"
-
}
-
}
-
-
1
describe "GET /index" do
-
-
1
it "index renders a successful response" do
-
1
AccountBlock::SellerDocument.create!(valid_attributes.merge(account_id: @account.id))
-
1
get "/account_block/accounts/#{@account.id}/seller_documents", headers: { token: @token }
-
1
expect(response).to be_successful
-
end
-
-
end
-
-
1
describe "GET /show" do
-
1
it "show renders a successful response" do
-
1
seller_document = AccountBlock::SellerDocument.create!(valid_attributes.merge(account_id: @account.id))
-
1
get "/account_block/accounts/#{@account.id}/seller_documents/#{seller_document.id}", headers: { token: @token }
-
1
expect(response).to be_successful
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("document_files")
-
end
-
-
1
it "show renders a error response" do
-
1
get "/account_block/accounts/#{@seller.id}/seller_documents/999" , params: { token: @token_s }
-
1
expect(JSON.parse(response.body)["errors"]).to eq("No Seller Document found")
-
end
-
end
-
-
1
describe "POST /create" do
-
1
context "with valid parameters" do
-
1
it "creates a new SellerDocument" do
-
1
expect {
-
1
post "/account_block/accounts/#{@account.id}/seller_documents", params: valid_attributes, headers: { token: @token }
-
}.to change(AccountBlock::SellerDocument, :count).by(1)
-
end
-
end
-
-
1
context "with invalid parameters" do
-
1
it "does not create a new SellerDocument" do
-
1
expect {
-
1
post "/account_block/accounts/#{@account.id}/seller_documents", params: invalid_attributes, headers: { token: @token }
-
}.to change(AccountBlock::SellerDocument, :count).by(0)
-
end
-
end
-
end
-
-
1
describe "PATCH /update" do
-
1
context "update with valid parameters" do
-
1
let(:new_attributes) {
-
{
-
1
document_name: "New Name"
-
}
-
}
-
-
1
it "updates the requested seller_document" do
-
1
seller_document = AccountBlock::SellerDocument.create!(valid_attributes.merge(account_id: @account.id))
-
1
patch "/account_block/accounts/#{@account.id}/seller_documents/#{seller_document.id}", params: new_attributes, headers: { token: @token }
-
1
seller_document.reload
-
1
expect(seller_document.document_name).to eq("License")
-
end
-
end
-
end
-
-
1
describe "POST /document_verification_email" do
-
1
context "with valid parameters document_verification_email" do
-
-
1
it "user not found" do
-
1
post "/account_block/accounts/document_verification_email", params: { token: @token, admin_email: 'admin@byezzy.com' }
-
1
expect(ActionMailer::Base.deliveries.count).to eq(0)
-
1
expect(JSON.parse(response.body)["message"]).to eq("User not found")
-
end
-
-
1
it "send email to vender / admin" do
-
1
post "/account_block/accounts/document_verification_email", params: { token: @token_s }
-
1
expect(ActionMailer::Base.deliveries.count).to eq(2)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Document verification email sent")
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::Accounts::SendOtpsController, type: :request do
-
1
before(:all) do
-
1
@account = create(:account, user_type: "buyer")
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
1
let(:params) {
-
{
-
4
"data": {
-
"attributes": {
-
"full_phone_number": "919876444210"
-
}
-
}
-
}
-
}
-
1
describe "POST create" do
-
1
send_otp_path = "/account_block/accounts/send_otps"
-
1
it "generates and returns OTP for a new account" do
-
1
allow_any_instance_of(AccountBlock::SmsOtp).to receive(:generate_pin_and_valid_date) do |sms_otp|
-
1
sms_otp.pin = '54321'
-
1
sms_otp.valid_until = Time.current + 5.minutes
-
end
-
1
stub_request(:post, "https://el.cloud.unifonic.com/rest/SMS/messages")
-
.with(
-
body: {
-
"AppSid" => ENV['UNIFONIC_APPSID'],
-
"Body" => "Your Pin Number is 54321",
-
"Recipient" => "+919876444210",
-
"SenderID" => ENV['UNIFONIC_SENDERID'],
-
"async" => "true"
-
},
-
headers: {
-
'Accept' => '*/*',
-
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
-
'Content-Type' => 'application/x-www-form-urlencoded',
-
'User-Agent' => 'Ruby'
-
}
-
)
-
.to_return(status: 200, body: "", headers: {})
-
1
post send_otp_path, params: params, headers: {token: @token}
-
1
expect(response).to have_http_status(:created)
-
-
end
-
-
1
it "generates and returns OTP for a new account in email" do
-
1
params[:data][:attributes][:full_phone_number] = @account.full_phone_number
-
1
allow_any_instance_of(AccountBlock::SmsOtp).to receive(:generate_pin_and_valid_date) do |sms_otp|
-
1
sms_otp.pin = '54321'
-
1
sms_otp.valid_until = Time.current + 5.minutes
-
end
-
1
stub_request(:post, "https://el.cloud.unifonic.com/rest/SMS/messages").
-
with(
-
body: {
-
"AppSid"=> ENV['UNIFONIC_APPSID'],
-
"Body"=>"Your Pin Number is 54321",
-
"Recipient"=> "+#{params[:data][:attributes][:full_phone_number]}",
-
"SenderID"=> ENV['UNIFONIC_SENDERID'],
-
"async"=>"true"
-
},
-
headers: {
-
'Accept'=>'*/*',
-
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
-
'Content-Type'=>'application/x-www-form-urlencoded',
-
'User-Agent'=>'Ruby'
-
}).
-
to_return(status: 200, body: "", headers: {})
-
1
post send_otp_path, params: params, headers: {token: @token}
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
-
end
-
-
1
it "returns an error for an already activated account" do
-
1
@account.update(activated: true)
-
1
params[:data][:attributes][:full_phone_number] = @account.full_phone_number
-
1
post send_otp_path, params: params, headers: {token: @token}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include("\"account\":\"Account already activated\"")
-
end
-
-
1
it "returns an error for failed OTP generation" do
-
1
params[:data][:attributes][:full_phone_number] = "2345"
-
1
post send_otp_path, params: params, headers: {token: @token}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include("\"Full phone number Invalid or Unrecognized Phone Number\"")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::Accounts::SmsConfirmationsController, type: :request do
-
-
1
describe 'POST create' do
-
5
let(:confirmation_path) { '/account_block/accounts/sms_otp_confirmations' }
-
5
let(:sms_otp) { create(:sms_otp) }
-
3
let(:token) { BuilderJsonWebToken.encode(sms_otp.id) }
-
2
let(:valid_params) { { pin: sms_otp.pin } }
-
5
let(:unifonic) {"https://el.cloud.unifonic.com/rest/SMS/messages"}
-
1
let(:headers) {{
-
4
'Accept'=>'*/*',
-
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
-
'Content-Type'=>'application/x-www-form-urlencoded',
-
'User-Agent'=>'Ruby'
-
}}
-
-
1
before do
-
4
stub_request(:post, unifonic)
-
.with(
-
body: {
-
"AppSid"=>ENV['UNIFONIC_APPSID'],
-
"Body"=>"Your Pin Number is #{sms_otp.pin}",
-
"Recipient"=> sms_otp.full_phone_number,
-
"SenderID"=>ENV['UNIFONIC_SENDERID'],
-
"async"=>"true"
-
},
-
headers: headers
-
)
-
.to_return(status: 200, body: "", headers: {})
-
end
-
-
1
context 'when the pin is valid' do
-
1
it 'confirms the phone number and returns a success response' do
-
-
1
post confirmation_path, params: valid_params, headers: {token: token}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include('Phone Number Confirmed Successfully')
-
1
expect(response.body).to include('token')
-
-
1
sms_otp.reload
-
1
expect(sms_otp.activated).to be true
-
end
-
end
-
-
1
context 'when the pin is invalid' do
-
2
let(:invalid_params) { { pin: '123456' } }
-
-
1
it 'returns an error response' do
-
1
post confirmation_path, params: invalid_params, headers: {token: token}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include('Invalid Pin for Phone Number')
-
-
1
sms_otp.reload
-
1
expect(sms_otp.activated).to be false
-
end
-
end
-
-
1
context 'when the SMS OTP has expired' do
-
2
let(:expired_sms_otp) { create(:sms_otp, activated: true) }
-
2
let(:exptoken) { BuilderJsonWebToken.encode(expired_sms_otp.id) }
-
2
let(:expired_params) { { pin: expired_sms_otp.pin } }
-
-
1
it 'returns an error response' do
-
1
stub_request(:post, unifonic)
-
.with(
-
body: {
-
"AppSid"=>ENV['UNIFONIC_APPSID'],
-
"Body"=>"Your Pin Number is #{expired_sms_otp.pin}",
-
"Recipient"=> expired_sms_otp.full_phone_number,
-
"SenderID"=>ENV['UNIFONIC_SENDERID'],
-
"async"=>"true"
-
},
-
headers: headers
-
)
-
.to_return(status: 200, body: "", headers: {})
-
1
expired_sms_otp.update(valid_until: 1.day.ago)
-
1
post confirmation_path, params: expired_params, headers: {token: exptoken}
-
-
1
expect(response).to have_http_status(:unauthorized)
-
1
expect(response.body).to include('This Pin has expired')
-
-
1
expect(AccountBlock::SmsOtp.exists?(expired_sms_otp.id)).to be false
-
end
-
end
-
-
1
context 'when the phone number is already activated' do
-
2
let(:activated_sms_otp) { create(:sms_otp, activated: true) }
-
2
let(:token) { BuilderJsonWebToken.encode(activated_sms_otp.id) }
-
2
let(:activated_params) { { pin: activated_sms_otp.pin } }
-
-
1
it 'returns a success response with a message' do
-
1
stub_request(:post, unifonic)
-
.with(
-
body: {
-
"AppSid"=>ENV['UNIFONIC_APPSID'],
-
"Body"=>"Your Pin Number is #{activated_sms_otp.pin}",
-
"Recipient"=> activated_sms_otp.full_phone_number,
-
"SenderID"=>ENV['UNIFONIC_SENDERID'],
-
"async"=>"true"
-
},
-
headers: headers
-
)
-
.to_return(status: 200, body: "", headers: {})
-
1
post confirmation_path, params: activated_params, headers: {token: token}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include('Phone Number Already Activated')
-
-
1
expect(activated_sms_otp.activated).to be true
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::SuggestionFeedbacksController, type: :request do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@suggestion_feedback = create(:suggestion_feedback)
-
1
@suggestion_feedbacks_url = "/account_block/suggestion_feedbacks"
-
end
-
-
1
let(:valid_attributes) {
-
{
-
2
"data": {
-
"attributes": {
-
"detail_type": "Suggestion",
-
"detail": "suggestion detail",
-
"first_name": "test",
-
"last_name": "user",
-
"email": "email@gmail.com"
-
}
-
}
-
}
-
}
-
-
1
let(:invalid_attributes) {
-
{
-
2
"data": {
-
"attributes": {
-
"detail_type": "Suggestion",
-
}
-
}
-
}
-
}
-
-
1
let(:valid_headers) {
-
7
{token: @token}
-
}
-
-
1
describe "GET /index" do
-
1
it "renders a successful response" do
-
1
get @suggestion_feedbacks_url, headers: valid_headers
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe "GET /show" do
-
1
it "renders a successful response" do
-
1
get "#{@suggestion_feedbacks_url}/#{@suggestion_feedback.id}", headers: valid_headers
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe "POST /create" do
-
1
context "with valid parameters" do
-
1
it "creates a new SuggestionFeedback" do
-
1
expect {
-
1
post @suggestion_feedbacks_url,
-
params: valid_attributes , headers: valid_headers
-
}.to change(AccountBlock::SuggestionFeedback, :count).by(1)
-
end
-
-
1
it "renders a JSON response with the new suggestion_feedback" do
-
1
post @suggestion_feedbacks_url,
-
params: valid_attributes , headers: valid_headers
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context "with invalid parameters" do
-
1
it "does not create a new SuggestionFeedback" do
-
1
expect {
-
1
post @suggestion_feedbacks_url,
-
params: invalid_attributes ,headers: valid_headers
-
}.to change(AccountBlock::SuggestionFeedback, :count).by(0)
-
end
-
-
1
it "renders a JSON response with errors for the new suggestion_feedback" do
-
1
post @suggestion_feedbacks_url,
-
params: invalid_attributes ,headers: valid_headers
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
# describe "PATCH /update" do
-
# context "with valid parameters" do
-
# let(:new_attributes) {
-
# skip("Add a hash of attributes valid for your model")
-
# }
-
-
# it "updates the requested suggestion_feedback" do
-
# suggestion_feedback = SuggestionFeedback.create! valid_attributes
-
# patch suggestion_feedback_url(suggestion_feedback),
-
# params: { suggestion_feedback: new_attributes }, headers: valid_headers, as: :json
-
# suggestion_feedback.reload
-
# skip("Add assertions for updated state")
-
# end
-
-
# it "renders a JSON response with the suggestion_feedback" do
-
# suggestion_feedback = SuggestionFeedback.create! valid_attributes
-
# patch suggestion_feedback_url(suggestion_feedback),
-
# params: { suggestion_feedback: new_attributes }, headers: valid_headers, as: :json
-
# expect(response).to have_http_status(:ok)
-
# expect(response.content_type).to match(a_string_including("application/json"))
-
# end
-
# end
-
-
# context "with invalid parameters" do
-
# it "renders a JSON response with errors for the suggestion_feedback" do
-
# suggestion_feedback = SuggestionFeedback.create! valid_attributes
-
# patch suggestion_feedback_url(suggestion_feedback),
-
# params: { suggestion_feedback: invalid_attributes }, headers: valid_headers, as: :json
-
# expect(response).to have_http_status(:unprocessable_entity)
-
# expect(response.content_type).to match(a_string_including("application/json"))
-
# end
-
# end
-
# end
-
-
1
describe "DELETE /destroy" do
-
1
it "destroys the requested suggestion_feedback" do
-
1
expect {
-
1
delete "#{@suggestion_feedbacks_url}/#{@suggestion_feedback.id}", headers: valid_headers
-
}.to change(AccountBlock::SuggestionFeedback, :count).by(-1)
-
1
body = JSON.parse(response.body)
-
1
expect(body['meta']['message']).to eq('Suggestion or Feedback Removed')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::UserDeliveryAddressesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account, user_type: 'buyer')
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@user_delivery_address = create(:user_delivery_address, account: @account)
-
end
-
-
1
let(:valid_params) do
-
{
-
3
token: @token,
-
account_id: @account.id,
-
data: {
-
attributes: {
-
"first_name": "test",
-
"last_name": "user",
-
"phone_number": "919922334453",
-
"address_1": "address 1",
-
"address_2": "address 2",
-
"city": "Bangalore",
-
"state": "Karnataka",
-
"zip_code": "560076",
-
"address_type": "Home",
-
"is_default": true
-
}
-
}
-
}
-
end
-
-
1
describe 'GET index' do
-
1
it 'returns a list of user delivery addresses' do
-
1
get :index, params: {account_id: @account.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'returns a user delivery address' do
-
1
get :show, params: {account_id: @account.id, id: @user_delivery_address.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'POST create' do
-
-
1
it 'renders errors if creation fails' do
-
1
post :create, params: {
-
token: @token,
-
account_id: @account.id,
-
data: {
-
attributes: {
-
first_name: nil
-
}
-
}
-
}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['errors']).to include("First name can't be blank")
-
end
-
-
1
it 'creates a new user delivery address' do
-
1
post :create, params: valid_params
-
1
expect(response).to have_http_status(:created)
-
1
expect(AccountBlock::UserDeliveryAddress.last.account).to eq(@account)
-
end
-
end
-
-
1
describe 'PATCH update' do
-
1
it 'updates an existing user delivery address' do
-
1
patch :update, params: valid_params.merge(id: @user_delivery_address.id)
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'renders errors if update fails' do
-
1
patch :update, params: {
-
token: @token,
-
account_id: @account.id,
-
id: @user_delivery_address.id,
-
data: {
-
attributes: {
-
address_1: nil
-
}
-
}
-
}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['errors']).to include("Address 1 can't be blank")
-
end
-
-
1
it 'updates an existing user delivery address and modifies associated order address_id' do
-
-
1
order = create(:shopping_cart_order, customer: @account)
-
# @user_delivery_address.update(is_default: true)
-
-
1
expect(order.address_id).to be_nil
-
-
1
patch :update, params: valid_params.merge(id: @user_delivery_address.id, is_default: true)
-
-
1
expect(response).to have_http_status(:ok)
-
-
1
order.reload
-
-
1
expect(order.address_id).to eq(@user_delivery_address.id)
-
end
-
end
-
-
1
describe 'DELETE destroy' do
-
1
it 'destroys a user delivery address' do
-
1
delete :destroy, params: {account_id: @account.id,token: @token, id: @user_delivery_address.id }
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['meta']['message']).to eq('Delivery Address Removed')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::BarcodesController, type: :controller do
-
-
1
before do
-
7
@account = FactoryBot.create(:account)
-
7
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@catalogue = create(:catalogue)
-
7
@barcode = create(:barcode, catalogue: @catalogue)
-
end
-
-
1
describe 'GET index' do
-
1
it 'returns a list of barcodes for a specific catalogue' do
-
1
barcode = create(:barcode, catalogue: @catalogue)
-
1
get :index, params: { catalogue_id: @catalogue.id, token: @token }
-
-
1
expect(response).to have_http_status(:success)
-
1
expect(JSON.parse(response.body).size).to eq(BxBlockCatalogue::Barcode.count)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'returns the details of a specific barcode' do
-
1
get :show, params: { catalogue_id: @catalogue.id, id: @barcode.id, token: @token }
-
-
1
expect(response).to have_http_status(:success)
-
1
expect(JSON.parse(response.body)['id']).to eq(@barcode.id)
-
end
-
-
1
it 'returns an error if barcode does not exist' do
-
1
get :show, params: { catalogue_id: @catalogue.id, id: 999, token: @token }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['message']).to eq("Barcode with id 999 doesn't exist")
-
end
-
end
-
-
1
describe 'POST create' do
-
2
let(:barcode_params) { { bar_code: '12345' } }
-
-
1
it 'creates a new barcode associated with the specified catalogue' do
-
1
post :create, params: { catalogue_id: @catalogue.id, barcode: barcode_params, token: @token }
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(BxBlockCatalogue::Barcode.last.catalogue).to eq(@catalogue)
-
end
-
-
1
it 'returns an error if barcode creation fails' do
-
1
post :create, params: { catalogue_id: @catalogue.id, barcode: {bar_code: ''}, token: @token }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)).to have_key('bar_code')
-
end
-
end
-
-
1
describe 'Patch update' do
-
2
let(:barcode_params) { { bar_code: '1up45' } }
-
-
1
it 'update a barcode associated with the specified catalogue' do
-
1
patch :update, params: {id: @barcode.id, catalogue_id: @catalogue.id, barcode: barcode_params, token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(BxBlockCatalogue::Barcode.last.catalogue).to eq(@catalogue)
-
end
-
-
1
it 'returns an error if barcode update fails' do
-
1
patch :update, params: { id: @barcode.id, catalogue_id: @catalogue.id, barcode: {bar_code: ''}, token: @token }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['bar_code'][0]).to eq("can't be blank")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::BrandsController, type: :controller do
-
1
before do
-
25
@account = FactoryBot.create(:account, user_type: 'seller')
-
25
@account_2 = FactoryBot.create(:account)
-
25
@token_2 = BuilderJsonWebToken.encode(@account_2.id, token_type: 'login')
-
25
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
25
@brand = create("brand",account: @account, branding_tradmark_certificate: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf")))
-
25
@category = create(:category)
-
25
@sub_category = create(:sub_category,category: @category)
-
25
@err_msg = "Brand name has already been taken"
-
end
-
-
1
describe 'POST #create' do
-
1
it 'creates a new brand' do
-
brand_params = {
-
1
brand_name: Faker::Lorem.word + rand(1..20000).to_s + Faker::Lorem.word,
-
brand_name_arabic: 'Brand in Arabic',
-
brand_website: 'https://www.example.com',
-
brand_year: 2023,
-
branding_tradmark_certificate: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf")),
-
brand_image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))
-
}
-
-
1
expect {
-
1
post :create, params: brand_params.merge(token: @token)
-
}.to change(BxBlockCatalogue::Brand, :count).by(1)
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)['data']['attributes']['brand_name']).to eq(brand_params[:brand_name])
-
end
-
-
1
it 'create with invalid params' do
-
1
brand_params = {brand_name: @brand.brand_name}
-
1
expect {
-
1
post :create, params: brand_params.merge(token: @token)
-
}.to change(BxBlockCatalogue::Brand, :count).by(0)
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq(@err_msg)
-
end
-
-
1
it 'create with same brand name as lower case(case sensitive)' do
-
1
brand_params = {brand_name: @brand.brand_name.downcase}
-
1
expect {
-
1
post :create, params: brand_params.merge(token: @token)
-
}.to change(BxBlockCatalogue::Brand, :count).by(0)
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq(@err_msg)
-
end
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a list of brands' do
-
-
1
get :index, params: { token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].size).to eq(BxBlockCatalogue::Brand.all.count)
-
end
-
end
-
-
1
describe 'GET #restricted_brands_index' do
-
1
it 'returns a list of brands restricted' do
-
-
1
get :restricted_brands_index, params: { token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].size).to eq(BxBlockCatalogue::Brand.all.where(restricted: true).count)
-
end
-
end
-
-
1
describe 'GET #approved_brands_index' do
-
1
it 'returns a list of brands approved' do
-
-
1
get :approved_brands_index, params: { token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].size).to eq(BxBlockCatalogue::Brand.all.where(approve: true).count)
-
end
-
end
-
-
1
describe 'GET #gated_brands_index' do
-
1
it 'returns a list of brands gated' do
-
1
get :gated_brands_index, params: { token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].size).to eq(BxBlockCatalogue::Brand.all.where(gated: true).count)
-
end
-
end
-
-
1
describe "GET #search_brand" do
-
1
it "returns matching brand based on the keyword search_brand" do
-
1
keyword = @brand.brand_name
-
-
1
get :search_brands, params: {token: @token, keyword: keyword}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body).size).to eq(1)
-
1
expect(JSON.parse(response.body)[0]["id"]).to eq(@brand.id)
-
1
expect(JSON.parse(response.body)[0]["brand_name"]).to eq(@brand.brand_name)
-
1
expect(JSON.parse(response.body)[0]["current_owner"]).to eq(true)
-
1
expect(JSON.parse(response.body)[0]["restricted_request_exist"]).to eq(false)
-
1
expect(JSON.parse(response.body)[0]["permission_granted"]).to eq(false)
-
end
-
-
1
it "returns an empty list if no matching brand found" do
-
1
keyword = "non_matching_keyword"
-
-
1
get :search_brands, params: {token: @token, keyword: "some_keyword" }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Brand not found")
-
end
-
-
1
it "returns an keyword missing error" do
-
-
1
get :search_brands, params: {token: @token, keyword: "" }
-
-
1
expect(response).to have_http_status(:bad_request)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Keyword is missing")
-
end
-
end
-
-
1
describe "GET #list brands from catalogues" do
-
1
it "returns matching brand based on the keyword list" do
-
1
category = FactoryBot.create(:category)
-
1
catalogue = FactoryBot.create(:catalogue, category: category, brand: @brand, status: true)
-
-
1
get :list_brands_from_catalogues, params: {token: @token, category_id: category.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(1)
-
1
expect(JSON.parse(response.body)["data"][0]["id"]).to eq(@brand.id.to_s)
-
1
expect(JSON.parse(response.body)["data"][0]["attributes"]["brand_name"]).to eq(@brand.brand_name)
-
end
-
-
1
it "returns matching brand based on the keyword by deal" do
-
1
catalogue1 = FactoryBot.create(:catalogue, brand: @brand, status: true)
-
1
deal = FactoryBot.create(:deal)
-
1
deal_catalogue = FactoryBot.create(:deal_catalogue, deal: deal, catalogue: catalogue1, seller: @account, status: 'approved' )
-
-
1
get :list_brands_from_catalogues, params: {token: @token, deal_id: deal.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"][0]["id"]).to eq(@brand.id.to_s)
-
1
expect(JSON.parse(response.body)["data"][0]["attributes"]["brand_name"]).to eq(@brand.brand_name)
-
end
-
-
1
it "returns an empty list if no matching brand found list" do
-
-
1
get :list_brands_from_catalogues, params: {token: @token, category_id: nil }
-
-
1
expect(response).to have_http_status(:bad_request)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Category ID or Deal ID is required")
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns brand' do
-
-
1
get :show, params: { token: @token , id: @brand.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("branding_tradmark_certificate")
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("brand_image")
-
end
-
end
-
-
1
describe 'GET #seller brands listing' do
-
1
it 'user not authorized' do
-
1
get :seller_brand_listing, params: { token: @token_2}
-
1
expect(response).to have_http_status(:forbidden)
-
1
expect(response.body).to eq("{\"errors\":[{\"message\":\"You are not authorized to access brands\"}]}")
-
end
-
-
1
it "get seller user's brands" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
get :seller_brand_listing, params: { token: @token}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'PUT #update_seller_brand' do
-
# it 'user not authorized' do
-
# put :update_seller_brands, params: { token: @token}
-
# expect(response).to have_http_status(:forbidden)
-
# expect(response.body).to eq("{\"errors\":[{\"message\":\"You are not authorized to access brands\"}]}")
-
# end
-
-
1
it "update seller's brand" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
put :update_seller_brands, params: { token: @token, id: @brand.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it "not update seller's brand" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
put :update_seller_brands, params: { token: @token, id: @brand.id, brand_name: nil}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to eq("{\"errors\":[\"Brand name can't be blank\"]}")
-
end
-
end
-
-
1
describe 'POST #update_seller_brand' do
-
1
it 'user not authorized' do
-
1
post :create_seller_brand, params: { token: @token_2}
-
1
expect(response).to have_http_status(:forbidden)
-
1
expect(response.body).to eq("{\"errors\":[{\"message\":\"You are not authorized to access brands\"}]}")
-
end
-
-
1
it "create seller brand" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
post :create_seller_brand, params: { token: @token, brand_name: "lenovo", brand_name_arabic: "lenovo", brand_website: "https://example.com"}
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it "not create seller's brand" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
post :create_seller_brand, params: { token: @token, brand_name: nil, brand_website: nil}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to eq("{\"errors\":[\"Brand name can't be blank\",\"Brand website can't be blank\",\"Brand website is not valid url\"]}")
-
end
-
end
-
-
1
describe 'DELETE #delete_seller_brand' do
-
1
before do
-
2
@accountb = FactoryBot.create(:account, user_type: 'seller')
-
2
@token_b = BuilderJsonWebToken.encode(@accountb.id, token_type: 'login')
-
2
@brand_b = create(:brand)
-
2
@brand_c = create(:brand)
-
2
@catalogueb = create(:catalogue, brand: @brand_c)
-
end
-
-
1
it "delete seller brand" do
-
1
delete :delete_seller_brand, params: { token: @token_b, id: @brand_b.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it "delete seller brand associated with catalogue" do
-
1
delete :delete_seller_brand, params: { token: @token_b, id: @brand_c.id}
-
1
expect(JSON.parse(response.body)["errors"][0]).to eq("Cannot delete brand because it is associated with products or store.")
-
end
-
end
-
-
1
describe "GET #list_sub_categories_from_brand" do
-
-
1
it "error message list_sub_categories_from_brand" do
-
-
1
get :list_sub_categories_from_brand, params: {brand_id: nil}
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["error"]).to eq("subcategories not found")
-
end
-
-
1
it "returns a list of list_sub_categories_from_brand by brand" do
-
-
1
brand = FactoryBot.create(:brand, approve: true)
-
1
catalogue = FactoryBot.create(:catalogue, brand: brand, category: @category, sub_category: @sub_category, status: true)
-
1
get :list_sub_categories_from_brand, params: {brand_id: brand.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(1)
-
1
expect(JSON.parse(response.body)["data"][0]['id']).to eq(@sub_category.id.to_s)
-
end
-
end
-
end
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::CatalogueContentsController, type: :controller do
-
-
1
before do
-
5
@account = FactoryBot.create(:account)
-
5
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
5
@catalogue = create(:catalogue)
-
5
@custom_field = create(:custom_field)
-
5
@catalogue_content = create(:catalogue_content, catalogue: @catalogue,custom_field: @custom_field )
-
-
5
@category = FactoryBot.create(:category)
-
5
@sub_category = FactoryBot.create(:sub_category)
-
5
@mini_category = FactoryBot.create(:mini_category)
-
5
@micro_category = FactoryBot.create(:micro_category)
-
-
5
@custom_field1 = FactoryBot.create(:custom_field, field_name: 'Field1', fieldable: @category)
-
5
@custom_field2 = FactoryBot.create(:custom_field, field_name: 'Field2', fieldable: @sub_category)
-
5
@custom_field3 = FactoryBot.create(:custom_field, field_name: 'Field3', fieldable: @mini_category)
-
5
@custom_field4 = FactoryBot.create(:custom_field, field_name: 'Field4', fieldable: @micro_category)
-
-
5
@catalogue_content1 = FactoryBot.create(:catalogue_content, custom_field: @custom_field1, catalogue: @catalogue)
-
5
@catalogue_content2 = FactoryBot.create(:catalogue_content, custom_field: @custom_field2, catalogue: @catalogue)
-
5
@catalogue_content3 = FactoryBot.create(:catalogue_content, custom_field: @custom_field3, catalogue: @catalogue)
-
5
@catalogue_content4 = FactoryBot.create(:catalogue_content, custom_field: @custom_field4, catalogue: @catalogue)
-
end
-
-
-
1
describe 'GET index' do
-
1
it 'returns a list of catalogue contents' do
-
-
1
get :index, params: { catalogue_id: @catalogue.id , token: @token}
-
1
expect(response).to have_http_status(:ok)
-
-
1
expect(JSON.parse(response.body)['data'].size).to eq(5)
-
end
-
end
-
-
1
describe 'POST create' do
-
1
it 'creates catalogue contents' do
-
content_params = [
-
1
{ custom_field_id: @custom_field.id, value: 'Value 1', custom_field_name: @custom_field.field_name }
-
]
-
-
1
post :create, params: { catalogue_id: @catalogue.id, catalogue_contents_entries: content_params , token: @token}
-
1
expect(response).to have_http_status(:created)
-
-
1
expect(JSON.parse(response.body)['data'].size).to eq(1)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['value']).to eq(content_params[0][:value])
-
end
-
end
-
-
1
describe 'PUT update_catalogue_contents' do
-
1
it 'updates catalogue contents' do
-
-
-
updated_content_params = [
-
1
{ id: @catalogue_content.id, custom_field_id: @catalogue_content.custom_field_id, value: 'Updated Value', custom_field_name: 'Updated Field' }
-
]
-
-
1
put :update_catalogue_contents, params: { catalogue_id: @catalogue.id, catalogue_contents_entries: updated_content_params, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
-
1
expect(JSON.parse(response.body)['data'].size).to eq(1)
-
-
1
updated_content = BxBlockCatalogue::CatalogueContent.find_by(id: @catalogue_content.id)
-
1
expect(updated_content.value).to eq('Updated Value')
-
1
expect(updated_content.custom_field_name).to eq('Updated Field')
-
end
-
end
-
-
1
describe 'DELETE delete_catalogue_contents' do
-
1
it 'deletes catalogue contents' do
-
-
1
contents_to_delete = create_list(:catalogue_content, 3, catalogue: @catalogue, custom_field: @custom_field)
-
-
1
content_ids_to_delete = contents_to_delete.map(&:id)
-
-
1
delete :delete_catalogue_contents, params: { catalogue_id: @catalogue.id, ids: content_ids_to_delete , token: @token}
-
1
expect(response).to have_http_status(:ok)
-
-
1
remaining_contents = BxBlockCatalogue::CatalogueContent.where(id: content_ids_to_delete)
-
1
expect(remaining_contents).to be_empty
-
end
-
end
-
-
1
describe 'GET fetch_custom_field_filters' do
-
1
it 'returns custom field values filtered by categories' do
-
1
get :fetch_custom_field_filters, params: {
-
category_ids: [@category.id],
-
sub_category_ids: [@sub_category.id],
-
mini_category_ids: [@mini_category.id],
-
micro_category_ids: [@micro_category.id],
-
token: @token
-
}
-
-
1
expect(response).to have_http_status(:ok)
-
-
1
result = JSON.parse(response.body)
-
1
expect(result['custom_field_values']['Field1']).to match_array([@catalogue_content1.value])
-
1
expect(result['custom_field_values']['Field2']).to match_array([@catalogue_content2.value])
-
1
expect(result['custom_field_values']['Field3']).to match_array([@catalogue_content3.value])
-
1
expect(result['custom_field_values']['Field4']).to match_array([@catalogue_content4.value])
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::CataloguesController, type: :controller do
-
-
1
before do
-
50
sample_image_path = Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg')
-
50
sample_image = File.open(sample_image_path, 'rb').read
-
50
stub_request(:get, "https://fastly.picsum.photos/id/20/3670/2462.jpg?hmac=CmQ0ln-k5ZqkdtLvVO23LjVAEabZQx2wOaT4pyeG10I").
-
with(
-
headers: {
-
'Accept'=>'*/*',
-
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
-
'User-Agent'=>'Ruby',
-
}).
-
to_return(status: 200, body: sample_image, headers: {'Content-Type' => 'image/jpeg'})
-
end
-
-
1
account = FactoryBot.create(:account, user_type: "seller")
-
1
seller2 = FactoryBot.create(:account, user_type: "seller")
-
1
buyer = FactoryBot.create(:account, user_type: "buyer")
-
1
token = BuilderJsonWebToken.encode(account.id, token_type: 'login')
-
1
category = FactoryBot.create(:category)
-
1
custom_field = FactoryBot.create(:custom_field, field_name: 'Old Field Name',fieldable: category)
-
1
brand = FactoryBot.create(:brand)
-
1
restricted_brand = FactoryBot.create(:brand, restricted: true)
-
1
subcategory = FactoryBot.create(:sub_category, category: category)
-
1
minicategory = FactoryBot.create(:mini_category, sub_category: subcategory)
-
1
microcategory = FactoryBot.create(:micro_category,mini_category: minicategory)
-
1
microcategory_2 = FactoryBot.create(:micro_category,mini_category: minicategory)
-
1
custom_field_2 = FactoryBot.create(:custom_field, field_name: 'mandatory',fieldable: microcategory_2, mandatory: true)
-
1
parent_catalogue = FactoryBot.create(:parent_catalogue, category: category, brand: brand, status: true)
-
1
catalogue = FactoryBot.create(:catalogue, parent_catalogue: parent_catalogue, category: category,sub_category: subcategory,mini_category: minicategory, micro_category: microcategory, brand: brand, status: true, seller: account)
-
1
product_content = FactoryBot.create(:product_content, catalogue: catalogue, feature_bullets_attributes: [{value: "feature 1"}], image_urls_attributes: [{url: "www.img1.com"}])
-
1
low_stock_prod = FactoryBot.create(:catalogue, category: category,sub_category: subcategory,mini_category: minicategory, micro_category: microcategory, brand: brand, status: true, seller: account, stocks: 0)
-
1
lsp_product_content = FactoryBot.create(:product_content, catalogue: low_stock_prod, feature_bullets_attributes: [{value: "feature 2"}], image_urls_attributes: [{url: "www.img2.com"}])
-
1
favourite = FactoryBot.create(:favourite, user_id: buyer.id, favouriteable_id: catalogue.id)
-
1
review_seller = FactoryBot.create(:review, reviewer_id: buyer.id, catalogue: catalogue, account_id: account.id,review_type: 'seller', is_approved: true )
-
1
review_catalogue = FactoryBot.create(:review, rating: 4, reviewer_id: buyer.id, catalogue: catalogue, account_id: account.id,review_type: 'product', is_approved: true )
-
1
deal = FactoryBot.create(:deal)
-
1
deal_catalogue = FactoryBot.create(:deal_catalogue, deal: deal, catalogue: catalogue, seller: seller2, status: 'approved' )
-
1
rating = 4
-
1
reviews = FactoryBot.create_list(:review, 3, reviewer_id: buyer.id, catalogue: catalogue, account_id: account.id, rating: rating, review_type: 'product', is_approved: true)
-
1
search_catalogue_error = "Seller SKU not found"
-
catalogue_params = {
-
1
parent_catalogue_id: parent_catalogue.id,
-
category_id: category.id,
-
sub_category_id: subcategory.id,
-
mini_category_id: minicategory.id,
-
micro_category_id: microcategory.id,
-
brand_id: brand.id,
-
sku: Faker::Alphanumeric.alphanumeric(number: 14, min_numeric: 5),
-
besku: parent_catalogue.besku,
-
product_image: Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg')),
-
status: 'active'
-
}
-
-
1
file_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
-
1
ship_unit = ['Centimeter','Meter','Inch','Feet']
-
columns_and_values = {
-
1
'Category': category&.name,
-
'SubCategory': subcategory&.name,
-
'MiniCategory': minicategory&.name,
-
'Micro Category': microcategory&.name,
-
'Brand Name': brand&.brand_name,
-
'Seller SKU': nil,
-
'Product Title': nil,
-
'Product Image': nil,
-
'GTIN': nil,
-
'MRP': nil,
-
'Retail Price': nil,
-
'Long Description': nil,
-
'Whats in the Package': nil,
-
251
'Country of Origin': CS.countries.map { |c| c[1] },
-
'Product Color': ["Purple", "Light Coral","Lime Green", "Yellow", "Grey", "Ocean Green", "Pink", "Sky blue"],
-
'Warranty Days': nil,
-
'Warranty Months': nil,
-
'Feature Bullet 1': nil,
-
'Feature Bullet 2': nil,
-
'Feature Bullet 3': nil,
-
'Feature Bullet 4': nil,
-
'Size': nil,
-
'Size Unit': ['Grams','KiloGrams','Centimeter','Millimeter'],
-
'Capacity': nil,
-
'Capacity Unit': ['Litre','Millilitre'],
-
'HS Code': nil,
-
'Prod Model Name': nil,
-
'Prod Model Number': nil,
-
'Number of Pieces': nil,
-
'Shipping Length': nil,
-
'Shipping Length Unit': ship_unit,
-
'Shipping Height': nil,
-
'Shipping Height Unit': ship_unit,
-
'Shipping Width': nil,
-
'Shipping Width Unit': ship_unit,
-
'Shipping Weight': nil,
-
'Shipping Weight Unit': ['Kilogram','Gram','Ounce (OZ)','pound (lb)'],
-
'Image URL 1': nil,
-
'Image URL 2': nil,
-
'Image URL 3': nil,
-
'Image URL 4': nil,
-
'Image URL 5': nil,
-
'Image URL 6': nil,
-
"#{custom_field.field_name}": custom_field.custom_fields_options.map(&:option_name)
-
}
-
1
csv_header = columns_and_values.keys.map(&:to_s)
-
1
prod_image = "https://fastly.picsum.photos/id/20/3670/2462.jpg?hmac=CmQ0ln-k5ZqkdtLvVO23LjVAEabZQx2wOaT4pyeG10I"
-
1
csv_file_path = Rails.root.join('spec', 'fixtures', 'files/product_upload_template_valid.xlsx')
-
1
invalid_csv_file_path = Rails.root.join('spec', 'fixtures', 'files/product_upload_template_invalid.xlsx')
-
-
1
def generate_csv_file(data, file_path)
-
3
workbook = WriteXLSX.new(file_path)
-
3
worksheet = workbook.add_worksheet
-
-
3
data.each_with_index do |row, row_index|
-
16
row.each_with_index do |cell, col_index|
-
514
worksheet.write(row_index, col_index, cell)
-
end
-
end
-
3
workbook.close
-
end
-
-
-
1
describe 'POST create' do
-
1
it 'creates a new catalogue and returns status :created' do
-
1
post :create, params: catalogue_params.merge({token: token})
-
-
1
expect(response).to have_http_status(:created)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['category_id']).to eq(category.id)
-
1
expect(json_response['data']['attributes']['sub_category']['name']).to eq(subcategory.name)
-
1
expect(json_response['data']['attributes']['mini_category']['name']).to eq(minicategory.name)
-
1
expect(json_response['data']['attributes']['micro_category']['name']).to eq(microcategory.name)
-
1
expect(json_response['data']['attributes']['besku']).to eq(parent_catalogue.besku)
-
1
expect(json_response['data']['attributes']['final_price']).to eq("0.0")
-
1
expect(BxBlockActivitylog::ActivityLog.find_by(user_id: account.id).action).to eq("Product Created!")
-
end
-
-
1
it 'returns status :unprocessable_entity if the catalogue creation fails' do
-
1
post :create, params: catalogue_params.merge({token: token}).except(:category_id)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['errors']).to eq(["Category must exist"])
-
end
-
end
-
-
1
describe 'GET show' do
-
1
before do
-
3
request.headers['Authorization'] = token
-
end
-
-
1
context 'when the catalogue exists with an active offer' do
-
1
let(:catalogue) { FactoryBot.create(:catalogue, parent_catalogue: parent_catalogue, category: category, sub_category: subcategory, mini_category: minicategory, micro_category: microcategory, brand: brand, status: true, seller: account) }
-
2
let!(:catalogue_offer) { FactoryBot.create(:catalogue_offer, catalogue: catalogue, sale_schedule_from: Date.today, sale_schedule_to: Date.today) }
-
-
1
it 'updates the catalogue price details and returns status :ok' do
-
1
get :show, params: { id: catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
-
1
expect(json_response['data']['attributes']['final_price']).to eq(catalogue.calculate_effective_price.to_s)
-
1
expect(json_response['data']['attributes']['offer_percentage']).to eq(catalogue.calculate_offer_percentage)
-
1
expect(json_response['data']['attributes']['stroked_price']).to eq(catalogue.calculate_stroked_price)
-
end
-
end
-
-
1
context 'when the catalogue exists without an active offer' do
-
1
let(:catalogue) { FactoryBot.create(:catalogue, parent_catalogue: parent_catalogue, category: category, sub_category: subcategory, mini_category: minicategory, micro_category: microcategory, brand: brand, status: true, seller: account) }
-
2
let!(:catalogue_offer) { FactoryBot.create(:catalogue_offer, catalogue: catalogue, sale_schedule_from: Date.today + 1, sale_schedule_to: Date.today + 2) }
-
-
1
it 'sets offer_percentage to 0.0 and returns status :ok' do
-
1
get :show, params: { id: catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
-
1
expect(json_response['data']['attributes']['offer_percentage']).to eq(0.0)
-
end
-
end
-
-
1
context 'when the catalogue does not exist' do
-
1
it 'returns status :not_found' do
-
1
get :show, params: { id: 99999 } # Assuming ID does not exist
-
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
end
-
-
1
describe 'GET Sku validate' do
-
1
it 'returns the sku params missing' do
-
-
1
get :sku_validate, params: { token: token }
-
-
1
expect(response).to have_http_status(:bad_request)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['message']).to eq('SKU parameter is missing')
-
end
-
-
1
it 'returns status :conflict if the catalogue is exist' do
-
1
get :sku_validate, params: { token: token,sku: catalogue.sku }
-
-
1
expect(response).to have_http_status(:conflict)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['message']).to eq('Already exist in database')
-
end
-
-
1
it 'returns status :ok if the catalogue is not exist' do
-
1
get :sku_validate, params: { token: token,sku: "a1#{Faker::Alphanumeric.alphanumeric(number: 14, min_numeric: 5)}b1" }
-
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['message']).to eq('SKU is valid')
-
end
-
end
-
-
1
describe 'GET index' do
-
1
catalogue_list = FactoryBot.create_list(:catalogue,2, parent_catalogue: parent_catalogue, category: category, brand: brand, seller: account)
-
1
it 'returns all catalogues' do
-
-
1
get :index, params: {token: token}
-
-
1
expect(response).to have_http_status(:ok)
-
# expect(JSON.parse(response.body)['data'].map(&:id)).to include(catalogue_list.last.id.to_s)
-
end
-
-
1
it 'returns all catalogues sort by whats_new' do
-
-
1
get :index, params: {token: token, sort_by: 'whats_new'}
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns all catalogues search by fulfillment content_status and live_status' do
-
1
get :index, params: {
-
token: token,
-
fulfillment: ["byezzy"],
-
content_status: ["accepted"],
-
live_status: [true]
-
}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns all catalogues sort by popularity' do
-
-
1
get :index, params: {token: token, sort_by: 'popularity'}
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns all searched catalogues' do
-
-
1
get :index, params: {token: token, search: brand.brand_name}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)).to include('data')
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['final_price']).to be_an_instance_of(String)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['brand_id']).to eq(brand.id)
-
end
-
end
-
-
1
describe 'GET search_catalogues_by_brand' do
-
1
brand_catalogue_list = FactoryBot.create_list(:catalogue,2, category: category, micro_category: microcategory, brand: brand, seller: account)
-
1
catalogue_prod_content = FactoryBot.create(:product_content, catalogue: brand_catalogue_list.last, feature_bullets_attributes: [{value: "feature 3"}], image_urls_attributes: [{url: "www.img3.com"}])
-
1
it 'returns all catalogues by brands' do
-
-
1
get :search_catalogues_by_brand, params: {token: token, brand_id: brand.id, micro_category_id: microcategory.id}
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns all searched catalogues by title&brand' do
-
-
1
get :search_catalogues_by_brand, params: {token: token, micro_category_id: microcategory.id, brand_id: brand.id, product_keyword: catalogue_prod_content.product_title}
-
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['product_content']['product_attributes']['product_title']).to eq(catalogue_prod_content.product_title)
-
end
-
-
end
-
-
1
describe 'PATCH update' do
-
1
it 'updates the specified catalogue and returns status :ok' do
-
-
1
patch :update, params: { token: token,
-
id: catalogue.id,
-
status: 'inactive'
-
}
-
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['status']).to eq(true)
-
1
expect(json_response['data']['attributes']['product_content']['custom_fields_contents'].last['custom_field_name']).to include(custom_field.field_name)
-
end
-
-
1
it 'returns status :not_found if the catalogue is not found' do
-
1
patch :update, params: { token: token, id: 0, status: 'inactive' }
-
-
1
expect(response).to have_http_status(:not_found)
-
end
-
-
1
it 'returns status :unprocessable_entity if the catalogue update fails' do
-
1
patch :update, params: { token: token,
-
id: catalogue.id,
-
brand_id: nil
-
}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['errors']).to eq(["Brand must exist"])
-
end
-
end
-
-
1
describe "GET #search_catalogue" do
-
1
it "returns matching catalogue based on the keyword" do
-
1
variant_product = FactoryBot.create(:catalogue, sku: catalogue.sku, parent_product: catalogue, is_variant: true,seller: account)
-
1
product_variant_group = FactoryBot.create(:product_variant_group, catalogue: catalogue, variant_product: variant_product)
-
-
1
get :search_catalogues, params: {token: token, keyword: variant_product.product_variant_group.product_sku}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(2)
-
1
expect(JSON.parse(response.body)["data"][0]["attributes"]["sku"]).to eq(catalogue.sku)
-
1
expect(JSON.parse(response.body)["data"][1]["attributes"]["sku"]).to eq(variant_product.sku)
-
1
expect(JSON.parse(response.body)["data"][1]["attributes"]["variant_product_group"]['product_bibc']).to eq(variant_product.product_variant_group.product_bibc)
-
end
-
-
1
it "returns an empty list if no matching catalogue found" do
-
1
keyword = "non_matching_keyword"
-
-
1
get :search_catalogues, params: {token: token, keyword: "some_keyword" }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq(search_catalogue_error)
-
end
-
-
1
it "returns an catalogue which doesnt have offer" do
-
1
off_product = FactoryBot.create(:catalogue, seller: account)
-
1
offerp = FactoryBot.create(:catalogue_offer, catalogue: off_product, status: true)
-
-
1
get :search_catalogues, params: {token: token, keyword: off_product.sku }
-
-
1
expect(JSON.parse(response.body)["message"]).to eq(search_catalogue_error)
-
end
-
end
-
-
1
describe 'GET template_download' do
-
1
it 'returns a JSON file with the correct headers and values' do
-
1
get :template_download, params: {
-
category_id: category.id,
-
subcategory_id: subcategory.id,
-
minicategory_id: minicategory.id,
-
microcategory_id: microcategory.id,
-
brand_id: brand.id,
-
token: token
-
}
-
-
1
expect(response).to have_http_status(:success)
-
-
1
json_response = JSON.parse(response.body)
-
-
1
expect(json_response['headers']).to eq(csv_header)
-
-
1
values = json_response['values'].transform_keys(&:to_sym)
-
-
1
expect(values).to eq(columns_and_values)
-
end
-
end
-
-
1
describe 'POST bulk_upload' do
-
-
1
before(:all) do
-
1
FileUtils.mkdir_p(File.dirname(csv_file_path))
-
1
sku_1 = Faker::Alphanumeric.alphanumeric(number: 14, min_numeric: 5)
-
1
sku_2 = Faker::Alphanumeric.alphanumeric(number: 14, min_numeric: 5)
-
1
custom_option = "My Option"
-
-
csv_data = [
-
1
csv_header,
-
[category.name, subcategory.name, minicategory.name, microcategory.name, brand.brand_name,sku_1,"Product Title10",prod_image,Faker::Number.number(digits: 9),100,234,"lonnnnnnnnnnnnnnnnnng descrippppppppppppion","wts","India","grey","","","ahjd","def","FB1","","","","","","","","","","","","","","","","","","","","https://www.sjd.com","","","",custom_option],
-
[category.name, subcategory.name, minicategory.name, microcategory.name, brand.brand_name,sku_2,"Product Title20","",Faker::Number.number(digits: 9),100,234,"lonnnnnnnnnnnnnnnnng descripppppppppppion","wts","India","grey","","","shdj","djf","FB1","","","","","","","","","","","","","","","","","","","","https://www.sjd2.com","","","",custom_option],
-
]
-
-
csv_invalid_data = [
-
1
csv_header,
-
['unknown12cat', subcategory.name, minicategory.name, microcategory.name, brand.brand_name,Faker::Alphanumeric.alpha(number: 5),"Product Title11",prod_image,parent_catalogue.besku],
-
[category.name, subcategory.name, 'unknownminicat', microcategory.name, brand.brand_name,Faker::Alphanumeric.alpha(number: 5),"Product Title12",prod_image,parent_catalogue.besku],
-
[category.name, 'unknownsubcat', minicategory.name, microcategory.name, brand.brand_name,Faker::Alphanumeric.alpha(number: 5),"Product Title13",prod_image,parent_catalogue.besku],
-
[category.name, subcategory.name, minicategory.name, 'unknownmicrocat', brand.brand_name,Faker::Alphanumeric.alpha(number: 5),"Product Title14",prod_image,""],
-
[category.name, subcategory.name, minicategory.name, microcategory.name, brand.brand_name,catalogue.sku,"Product Title15",prod_image,nil,"",100,234,"lonnnnnnnnnnnnnnnnng descrippp2pppppppion","","India","grey","","","FB1","","","","","","","","","","","","","","","","","","","httpp//","www."],
-
[category.name, subcategory.name, minicategory.name, microcategory.name, restricted_brand.brand_name,"asdfdf","Product Title16"],
-
[category.name, subcategory.name, minicategory.name, microcategory.name, brand.brand_name,"valid123valid","tile 1",prod_image,Faker::Number.number(digits: 9),100,234,"lonnnnnnnnnn2nnnng descripppppppppppion","Product Titl20","India","grey","","","FB1","","","","","","","","","prod 6","","",4,"mc",7,"cm","","","","","","","","",custom_option],
-
[category.name, subcategory.name, minicategory.name, microcategory.name, brand.brand_name,"valid123valid","title 8",prod_image,Faker::Number.number(digits: 9),100,234,"lonnnnnnnnnnnnnnnnng descripppppppppppion","wts","India","grey","","","","","","","","","","","","","","","","","","","","","","","","","https://www.sjd3.com","","","",custom_option],
-
[category.name, subcategory.name, minicategory.name, microcategory.name, brand.brand_name,"valid13valid","title 9",prod_image,Faker::Number.number(digits: 9),100,234,"lonnnnnnnnnnnnnnnnng descrippppppppqpppion","wts1","India","grey","1234","","FB11","","","",2,"","","litre","","","","","3","","","meter","2","","","meter","","","https://www.sjd4.com","","","",custom_option],
-
csv_data[2]
-
]
-
-
1
generate_csv_file(csv_data, csv_file_path)
-
1
generate_csv_file(csv_invalid_data, invalid_csv_file_path)
-
end
-
-
2
let(:csv_file) { fixture_file_upload('files/product_upload_template_valid.xlsx', file_type) }
-
-
1
it 'creates catalogues from a valid CSV file' do
-
1
post :bulk_upload, params: { file: csv_file, token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['message']).to eq('Bulk upload completed successfully')
-
1
expect(json_response['successful_rows']).not_to be_empty
-
end
-
-
1
it 'handles validation errors in the CSV file' do
-
1
invalid_csv_file = fixture_file_upload('files/product_upload_template_invalid.xlsx', file_type)
-
-
1
post :bulk_upload, params: { file: invalid_csv_file, token: token }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['message']).to eq('Bulk upload completed with errors')
-
1
expect(json_response['skipped_rows']).not_to be_empty
-
1
expect(json_response['skipped_rows']).to include("Row 4: Microcategory not found or created.")
-
1
expect(json_response['validation_errors']).to include("Row 6: The brand '#{restricted_brand.brand_name}' you have selected has some restrictions for sellers or distributors,if you have products of the brand, please submit a permit to sell under this brand, and submit a request for approval.")
-
1
expect(json_response['validation_errors']).to include("Row 5: Validation error(s): SKU / Product is already added, Image urls url should start with 'https://' or 'www.', Country of origin can't be blank, Warranty days must be integer and no more than 3 digits, Product color is not a valid product color")
-
1
expect(json_response['validation_errors']).to include("Row 7: Validation error(s): Image urls url should start with 'https://' or 'www.', Shipping detail shipping length unit is not valid. It must be one of: Kilogram, Gram, Ounce (OZ), pound (lb), Centimeter, Meter, Inch, Feet, Shipping detail shipping height unit is not valid. It must be one of: Kilogram, Gram, Ounce (OZ), pound (lb), Centimeter, Meter, Inch, Feet")
-
1
expect(json_response['validation_errors']).to include("Row 8: Validation error(s): Feature bullets At least one feature bullet must be present")
-
1
expect(json_response['validation_errors']).not_to include("Row 8: Validation error(s): Unique psku can't be blank")
-
1
expect(json_response['validation_errors']).to include("Row 9: Validation error(s): Shipping detail shipping length unit must be present if shipping_length is provided, Shipping detail shipping height must be present if shipping_height_unit is provided, Shipping detail shipping width unit must be present if shipping_width is provided, Shipping detail shipping weight must be present if shipping_weight_unit is provided, Size and capacity size unit must be present if size is provided, Size and capacity capacity must be present if capacity_unit is provided, Warranty days must be integer and no more than 3 digits")
-
1
expect(json_response['successful_rows']).to include("Row 10: Uploaded successfully")
-
1
expect(json_response['validation_errors']).not_to be_empty
-
end
-
-
1
it 'handles an invalid file format' do
-
1
invalid_file = fixture_file_upload('files/document.doc')
-
-
1
post :bulk_upload, params: { file: invalid_file, token: token }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['error']).to eq('Invalid file format')
-
end
-
-
# it 'handles empty file csv' do
-
# empty_csv_file_path = Rails.root.join('spec', 'fixtures', 'files', 'empty_file.csv')
-
# FileUtils.touch(empty_csv_file_path)
-
-
# empty_csv_file = fixture_file_upload('files/empty_file.csv', file_type)
-
# post :bulk_upload, params: { file: empty_csv_file, token: token }
-
-
# expect(response).to have_http_status(:unprocessable_entity)
-
# json_response = JSON.parse(response.body)
-
# expect(json_response['error']).to eq("The uploaded file contains an invalid format. Error: Invalid byte sequence in UTF-8 in line 1. Please check the file and try again.")
-
# end
-
-
1
it 'handles empty file xlsx' do
-
1
empty_csv_file_path = Rails.root.join('spec', 'fixtures', 'files', 'empty_file.xlsx')
-
1
FileUtils.touch(empty_csv_file_path)
-
-
1
empty_csv_file = fixture_file_upload('files/empty_file.xlsx', file_type)
-
1
post :bulk_upload, params: { file: empty_csv_file, token: token }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['error']).to eq('The uploaded file does not contain any data.')
-
end
-
-
1
it 'handles missing mandatory custom fields' do
-
1
sku_3 = Faker::Alphanumeric.alphanumeric(number: 14, min_numeric: 5)
-
1
missing_custom_fields_csv_file_path = Rails.root.join('spec', 'fixtures', 'files', 'missing_custom_fields_file.xlsx')
-
1
generate_csv_file([csv_header, [category.name, subcategory.name, minicategory.name, microcategory_2.name, brand.brand_name,sku_3,"invaid test prod",prod_image,Faker::Number.number(digits: 9),310,284,"lonnnnnnnnnnng descppppppppppion","invaid test prod","India","grey","","","uyeiu","FB1","","","","","","","","","","","","","","","","","","","https://www.djhd.com"]], missing_custom_fields_csv_file_path)
-
1
missing_custom_fields_csv_file = fixture_file_upload('files/missing_custom_fields_file.xlsx', file_type)
-
-
1
post :bulk_upload, params: { file: missing_custom_fields_csv_file, token: token }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['skipped_rows']).not_to be_empty
-
1
expect(json_response['validation_errors']).to include("Row 1: Mandatory field '#{custom_field_2.field_name}' is missing")
-
end
-
-
end
-
-
1
describe 'GET list_catalogue_by_category' do
-
-
1
it 'returns products associated with the provided micro category' do
-
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, out_of_stocks: false, token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].first['attributes']['category']['name']).to include(category.name)
-
1
expect(JSON.parse(response.body)['data'].first['attributes']['sub_category']['name']).to include(subcategory.name)
-
1
expect(JSON.parse(response.body)['data'].first['attributes']['mini_category']['name']).to include(minicategory.name)
-
1
expect(JSON.parse(response.body)['data'].first['attributes']['micro_category']['name']).to include(microcategory.name)
-
2
expect(JSON.parse(response.body)['data'].map {|i| i['attributes']['stocks']}[0]).to be > 0
-
end
-
-
1
it 'returns products associated with the provided micro category' do
-
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, out_of_stocks: true, token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].last['attributes']['category']['name']).to include(low_stock_prod.category.name)
-
1
expect(JSON.parse(response.body)['total_count']).to eq(1)
-
end
-
-
1
it 'returns products associated with the provided brand' do
-
-
1
post :list_catalogue_by_category, params: { brand_id: brand.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].last['attributes']['brand_id']).to eq(brand.id)
-
end
-
-
1
it 'returns products associated with the provided deal' do
-
-
1
post :list_catalogue_by_category, params: { deal_id: deal.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].first['id']).to include(catalogue.id.to_s)
-
1
expect(JSON.parse(response.body)['data'].first['attributes']['deals'][0]['deal_name']).to include(deal.deal_name)
-
end
-
-
1
it 'returns no products if no category_id, sub_category_id, mini_category_id, or micro_category_id provided' do
-
1
post :list_catalogue_by_category, params: { category_id: 0 }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['message']).to eq('No products found')
-
1
expect(JSON.parse(response.body)['total_count']).to eq(0)
-
end
-
-
1
it 'filters products by custom field values' do
-
1
custom_field_values = ['value1', 'value2']
-
1
catalogue_content1 = FactoryBot.create(:catalogue_content, catalogue: catalogue, custom_field: custom_field, value: custom_field_values.first)
-
1
catalogue_content2 = FactoryBot.create(:catalogue_content, catalogue: catalogue, custom_field: custom_field, value: custom_field_values.second)
-
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, custom_field_values: custom_field_values, token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
2
expect(JSON.parse(response.body)['data'].map { |item| item['id'] }).to include(catalogue.id.to_s)
-
end
-
-
1
it 'filters products by rating' do
-
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, filter_by_rating: [rating], token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
2
expect(JSON.parse(response.body)['data'].map { |item| item['id'] }).to include(catalogue.id.to_s)
-
end
-
-
1
it 'filters products by rating with precise number' do
-
1
reviews.last.rating = 3.5
-
1
reviews.last.save
-
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, filter_by_rating: [reviews.last.rating], token: token }
-
-
2
expect(JSON.parse(response.body)['data'].map { |item| item['id'] }).to include(catalogue.id.to_s)
-
end
-
-
1
it 'sort products by rating' do
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, sort_by: "customer_rating", token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].first['id']).to include(catalogue.id.to_s)
-
end
-
-
1
it 'sort products by recommended' do
-
1
catalogue2 = FactoryBot.create(:catalogue, category: category,sub_category: subcategory,mini_category: minicategory, micro_category: microcategory, brand: brand, status: true, seller: account, recommended_priority: 9)
-
1
product_content2 = FactoryBot.create(:product_content, catalogue: catalogue2, feature_bullets_attributes: [{value: "feature 4"}], image_urls_attributes: [{url: "www.img4.com"}])
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sub_category_id: subcategory.id, mini_category_id: minicategory.id, micro_category_id: microcategory.id, sort_by: "recommended", token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].first['id']).to include(catalogue2.id.to_s)
-
end
-
-
1
it 'filter by product color' do
-
1
catalogue3 = FactoryBot.create(:catalogue, category: category,sub_category: subcategory,mini_category: minicategory, micro_category: microcategory, brand: brand, status: true, seller: account)
-
1
product_content3 = FactoryBot.create(:product_content, catalogue: catalogue3, product_color: "grey", feature_bullets_attributes: [{value: "feature 5"}], image_urls_attributes: [{url: "www.img5.com"}])
-
1
post :list_catalogue_by_category, params: { category_id: category.id, color_filter: ["grey"] }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'].first['id']).to include(catalogue3.id.to_s)
-
end
-
-
1
it 'filters products by price range' do
-
1
post :list_catalogue_by_category, params: { category_id: category.id, min_price: 10, max_price: 100, token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)).to include("data", "total_count", "message")
-
end
-
-
1
it 'returns no produncts when filtering by an out-of-range price' do
-
1
post :list_catalogue_by_category, params: { category_id: category.id, min_price: 1000, max_price: 2000, token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data']).to be_empty
-
end
-
-
1
it 'handles invalid sorting parameter gracefully' do
-
1
post :list_catalogue_by_category, params: { category_id: category.id, sort_by: "invalid", token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)).to include('data', 'total_count', 'message')
-
1
expect(JSON.parse(response.body)['data']).to be_an(Array)
-
1
expect(JSON.parse(response.body)['message']).to eq("Successfully Loaded")
-
end
-
end
-
-
1
describe 'get search_catalogues_by_title_or_brand_name' do
-
-
1
context 'when product and brand are provided' do
-
1
it 'returns matching catalogues for product and brand' do
-
1
get :search_catalogues_by_title_or_brand_name, params: { product_keyword: catalogue.product_title, brand_keyword: brand.brand_name, token: token }
-
1
expect(response).to have_http_status(:ok)
-
4
expect(JSON.parse(response.body)['data'].map { |item| item['id'] }).to include(catalogue.id.to_s)
-
end
-
-
1
it 'returns matching catalogues for product and brand' do
-
1
get :search_catalogues_by_title_or_brand_name, params: {token: token , product_keyword: catalogue.sku }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['sku']).to eq(catalogue.sku)
-
end
-
-
1
it 'returns products which doesnt have warehouse' do
-
1
warehouse_c1 = FactoryBot.create(:warehouse, account: account)
-
1
c1 = FactoryBot.create(:catalogue, seller: account)
-
1
prod_c1 = FactoryBot.create(:product_content, catalogue: c1)
-
1
warehouse_catalogue_c1 = FactoryBot.create(:warehouse_catalogue, warehouse: warehouse_c1, catalogue: c1, stocks: 8)
-
-
1
warehouse_c2 = FactoryBot.create(:warehouse, account: account)
-
1
c2 = FactoryBot.create(:catalogue, seller: account)
-
1
prod_c2 = FactoryBot.create(:product_content, catalogue: c2)
-
1
warehouse_catalogue_c1 = FactoryBot.create(:warehouse_catalogue, warehouse: warehouse_c2, catalogue: c2, stocks: 6)
-
-
1
get :search_catalogues_by_title_or_brand_name, params: {token: token, warehouse_id: warehouse_c2.id }
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['sku']).not_to eq(c1.sku)
-
end
-
-
1
it 'returns matching catalogues for products by brand' do
-
1
get :search_catalogues_by_title_or_brand_name, params: {token: token , product_keyword: catalogue.sku, brand_id: brand.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['sku']).to eq(catalogue.sku)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['brand_id']).to eq(brand.id)
-
end
-
-
1
it 'returns matching catalogues for products by brand' do
-
1
variant_product = FactoryBot.create(:catalogue, sku: catalogue.sku, parent_product: catalogue, is_variant: true, seller: account, brand: brand)
-
1
product_variant_group = FactoryBot.create(:product_variant_group, catalogue: catalogue, variant_product: variant_product)
-
1
get :search_catalogues_by_title_or_brand_name, params: {token: token , product_keyword: variant_product.product_variant_group.product_sku, brand_id: brand.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['sku']).to eq(variant_product.sku)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['brand_id']).to eq(brand.id)
-
end
-
end
-
-
1
context 'when only product keyword is provided' do
-
1
it 'returns matching catalogues based on the product' do
-
1
get :search_catalogues_by_title_or_brand_name, params: {token: token , brand_keyword: brand.brand_name }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['brand']['brand_name']).to include(brand.brand_name)
-
end
-
end
-
-
1
context 'when no matching products or brands are found' do
-
1
it 'returns a not found message' do
-
1
post :search_catalogues_by_title_or_brand_name, params: {token: token , product_keyword: 'Product3' }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['message']).to eq('No products found')
-
end
-
end
-
end
-
-
1
describe 'get list_store_menu_products' do
-
1
context 'when store menu provided' do
-
1
store = FactoryBot.create(:store)
-
1
catalogues = FactoryBot.create_list(:catalogue, 2)
-
1
menu = FactoryBot.create(:store_menu, store: store, catalogues: catalogues)
-
1
it 'returns matching catalogues for menu id' do
-
1
get :list_store_menu_products, params: { menu_id: menu.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['id']).to eq(catalogues.first.id.to_s)
-
end
-
-
1
context 'when no matching or menu are found' do
-
1
it 'returns a not found message for menu' do
-
1
post :list_store_menu_products, params: {menu_id: 0 }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['error']).to eq("Menu not found")
-
end
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::CatalogueOffersController, type: :controller do
-
-
1
before do
-
4
@account = FactoryBot.create(:account, user_type: 'seller')
-
4
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
5
let(:catalogue) { create(:catalogue) }
-
1
let(:product_content) { create(:product_content, catalogue: catalogue) }
-
2
let(:deal) { create(:deal, status: true) }
-
2
let(:deal_catalogue) { create(:deal_catalogue, deal: deal, catalogue: catalogue, seller: @account) }
-
3
let(:catalogue_offer) { create(:catalogue_offer, catalogue: catalogue) }
-
-
1
describe 'GET #show' do
-
1
it 'returns a successful response' do
-
1
get :show, params: { catalogue_id: catalogue.id, id: catalogue_offer.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
let(:valid_params) do
-
{
-
2
data: {
-
type: 'catalogue_offer',
-
attributes: {
-
barcode_id: create(:barcode, catalogue: catalogue).id,
-
price_info: 'Some price info',
-
bar_code_info: 'Some barcode info',
-
warranty: '1 year'
-
}
-
}
-
}
-
end
-
-
1
it 'creates a new catalogue offer' do
-
1
post :create, params: valid_params.merge(catalogue_id: catalogue.id,token: @token)
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it 'returns error if deal already exists' do
-
1
deal = create(:deal, status: true)
-
1
catalogue = create(:catalogue, seller: @account)
-
1
deal_catalogue = create(:deal_catalogue, deal: deal, catalogue: catalogue, seller: @account)
-
1
valid_params[:data][:attributes][:status] = true
-
-
1
post :create, params: valid_params.merge(catalogue_id: catalogue.id, token: @token)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Catalogue Cannot create an active offer as there is an active and approved deal for this product.")
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
let(:valid_params) do
-
{
-
1
data: {
-
type: 'catalogue_offer',
-
attributes: {
-
price_info: 'Updated price info',
-
sale_price: 230,
-
bar_code_info: 'Updated barcode info',
-
warranty: '2 years'
-
}
-
}
-
}
-
end
-
-
1
it 'updates the catalogue offer' do
-
1
catalogue.deal_catalogues << deal_catalogue
-
1
patch :update, params: valid_params.merge(catalogue_id: catalogue.id, id: catalogue_offer.id, token: @token)
-
1
expect(catalogue_offer.reload.warranty).to eq(valid_params[:data][:attributes][:warranty])
-
1
expect(deal_catalogue.reload.seller_price).to eq(valid_params[:data][:attributes][:sale_price])
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::CatalogueVariantsController, type: :controller do
-
1
before(:each) do
-
7
@account = FactoryBot.create(:account, user_type: 'seller')
-
7
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@catalogue = FactoryBot.create(:catalogue)
-
7
@catalogue_variant = FactoryBot.create(:catalogue_variant, seller: @account)
-
7
@variant_attribute = create(:variant_attribute, catalogue_variant: @catalogue_variant)
-
7
@atrribute_option = create(:attribute_option, variant_attribute: @variant_attribute)
-
7
@micro_category = create(:micro_category)
-
end
-
-
1
describe 'POST #create' do
-
1
let(:valid_params) do
-
{
-
2
token: @token,
-
seller_id: @account.id,
-
data: {
-
attributes: {
-
group_name: Faker::Lorem.word,
-
micro_category_id: @micro_category.id,
-
variant_attributes_attributes: [
-
{
-
attribute_name: 'size',
-
attribute_options_attributes: [
-
{ option: '6.1' },
-
{ option: '6.7' }
-
]
-
},
-
{
-
attribute_name: 'color',
-
attribute_options_attributes: [
-
{ option: 'red' },
-
{ option: 'blue' }
-
]
-
}
-
]
-
}
-
}
-
}
-
end
-
-
1
context 'with valid attributes' do
-
1
it 'creates a new CatalogueVariant' do
-
1
post :create, params: valid_params
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'with invalid attributes' do
-
1
it 'returns unprocessable entity status' do
-
1
invalid_params = valid_params.deep_merge(data: { attributes: { group_name: nil } })
-
1
post :create, params: invalid_params
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe 'GET #index' do
-
1
it '#index returns a success response' do
-
1
get :index, params: { token: @token }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it '#show returns a success response' do
-
1
get :show, params: { id: @catalogue_variant.id, token: @token}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'PUT #update' do
-
2
let(:updated_group_name) { 'updated group' }
-
1
let(:valid_update_params) do
-
{
-
1
token: @token,
-
seller_id: @account.id,
-
id: @catalogue_variant.id,
-
data: {
-
attributes: {
-
group_name: updated_group_name,
-
variant_attributes_attributes: [
-
{
-
id: @catalogue_variant.variant_attributes.first.id,
-
attribute_name: 'size',
-
attribute_options_attributes: [
-
{ id: @catalogue_variant.variant_attributes.first.attribute_options.first.id, option: 'new option' }
-
]
-
}
-
]
-
}
-
}
-
}
-
end
-
-
1
it 'updates the CatalogueVariant' do
-
1
put :update, params: valid_update_params.merge(token: @token)
-
1
@catalogue_variant.reload
-
1
expect(@catalogue_variant.group_name).to eq(updated_group_name)
-
end
-
end
-
-
1
describe 'GET #destroy' do
-
1
it '#destroy returns a success response' do
-
1
get :destroy, params: { id: @catalogue_variant.id, token: @token}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Variant group destroyed")
-
end
-
-
1
it '#destroy returns a error if variant exists' do
-
1
variant_group = create(:product_variant_group, catalogue_variant_id: @catalogue_variant.id)
-
1
get :destroy, params: { id: @catalogue_variant.id, token: @token}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["base"][0]).to eq("Selected group has variants linked to it. Please review and delete the variants to delete the group.")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::DealCataloguesController, type: :controller do
-
1
before do
-
11
@account = FactoryBot.create(:account, user_type: 'seller')
-
11
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
11
@deal = create(:deal, status: true)
-
11
@catalogue = create(:catalogue)
-
11
@product_content = create(:product_content, catalogue: @catalogue)
-
11
@deal_catalogue = create(:deal_catalogue, deal: @deal, catalogue: @catalogue, seller: @account)
-
11
@catalogue_2 = create(:catalogue, seller: @account)
-
11
@catalogue_3 = create(:catalogue, seller: @account)
-
11
@catalogue_4 = create(:catalogue, seller: @account)
-
11
@product_content2 = create(:product_content, catalogue: @catalogue_2)
-
11
@product_content3 = create(:product_content, catalogue: @catalogue_3)
-
11
@product_content4 = create(:product_content, catalogue: @catalogue_4)
-
11
@offer1 = create(:catalogue_offer, catalogue: @catalogue_2)
-
11
@offer2 = create(:catalogue_offer, catalogue: @catalogue_3)
-
11
@deal2 = create(:deal, discount_type: "flat", discount_value: 10, status: true)
-
11
@deal_catalogue2 = create(:deal_catalogue, deal: @deal2, catalogue: @catalogue_4, seller: @account)
-
end
-
-
1
let(:deal_catalogue_params) do {
-
2
seller_deals: [{
-
catalogue_id: @catalogue_3.id,
-
deal_price: "0",
-
seller_id: @account.id
-
}]
-
}
-
end
-
-
1
describe "GET #index" do
-
1
it "returns a list of deal catalogues" do
-
1
@deal_catalogues = create_list(:deal_catalogue,2, deal: @deal, catalogue: @catalogue_2, seller: @account, status: 2)
-
1
get :index, params: { token: @token, deal_id: @deal.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(3)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a deal catalogue" do
-
-
1
get :show, params: { token: @token, deal_id: @deal.id, id: @deal_catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@deal_catalogue.id.to_s)
-
end
-
-
1
it "returns a not found message if deal catalogue does not exist" do
-
1
non_existent_id = 999
-
-
1
get :show, params: { token: @token, deal_id: @deal.id, id: non_existent_id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Deal Catalogue not found")
-
end
-
end
-
-
1
describe "POST #create" do
-
1
it "creates a new deal catalogue" do
-
1
post :create, params: deal_catalogue_params.merge(token: @token, deal_id: @deal.id)
-
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it "creates a new deal catalogue flat" do
-
# if @deal.discount_type == 'flat'
-
# deal_catalogue_params[:seller_deals] = deal_catalogue_params[:seller_deals].map do |param|
-
# param.merge(deal_price: @deal.discount_value)
-
# end
-
# end
-
-
1
post :create, params: deal_catalogue_params.merge(token: @token, deal_id: @deal.id)
-
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['current_offer_price']).to eq(@offer1.sale_price.to_s)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['deal_id']).to eq(@deal.id)
-
end
-
-
1
it "returns errors if deal catalogue creation fails" do
-
1
catalogue_4 = create(:catalogue, seller: @account)
-
invalid_params = {
-
1
seller_deals: [{
-
catalogue_id: catalogue_4.id,
-
deal_price: 0.0,
-
seller_id: @account.id
-
},
-
{
-
catalogue_id: catalogue_4.id,
-
deal_price: 0.0,
-
seller_id: ""
-
}]
-
}
-
-
1
post :create, params: invalid_params.merge(token: @token, deal_id: @deal.id)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["error"]).to include("Validation failed: Seller must exist")
-
end
-
-
1
it "returns errors if deal catalogue already exists" do
-
1
catalogue_5 = create(:catalogue, seller: @account)
-
1
deal_catalogue2 = create(:deal_catalogue, deal: @deal, catalogue: catalogue_5, seller: @account)
-
-
invalid_params2 = {
-
1
seller_deals: [{
-
catalogue_id: catalogue_5.id,
-
deal_price: "234",
-
seller_id: @account.id
-
}]
-
}
-
-
1
patch :create, params: invalid_params2.merge(token: @token, deal_id: @deal.id)
-
-
1
expect(JSON.parse(response.body)["error"]).to include("A deal for this product already exists and is either in review, approved, or there is an active offer.")
-
end
-
end
-
-
1
describe "PATCH #update" do
-
1
updated_deal_price = "250.0"
-
1
let(:update_params) { {
-
2
data: {
-
attributes: {
-
deal_price: updated_deal_price
-
}
-
}
-
} }
-
1
it "updates a deal catalogue" do
-
-
1
patch :update, params: update_params.merge(token: @token, deal_id: @deal2.id, id: @deal_catalogue2.id)
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(@deal_catalogue2.reload.deal_price.to_s).to eq(updated_deal_price)
-
end
-
-
1
it "updates a deal catalogue flat price" do
-
1
@deal.discount_type = "flat"
-
1
@deal.save
-
1
update_params[:data][:attributes][:deal_price] = 0.0
-
-
1
patch :update, params: update_params.merge(token: @token, deal_id: @deal.id, id: @deal_catalogue.id)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response['data']['attributes']['deal_price']).to eq(@deal_catalogue.reload.deal_price.to_f.to_s)
-
end
-
-
1
it "returns errors if deal catalogue update fails" do
-
-
invalid_update_params = {
-
1
data: {
-
attributes: {
-
catalogue_id: nil
-
}
-
}
-
}
-
-
1
patch :update, params: invalid_update_params.merge(token: @token, deal_id: @deal.id, id: @deal_catalogue.id)
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Catalogue must exist")
-
end
-
end
-
-
1
describe "DELETE #destroy" do
-
1
it "destroys a deal catalogue" do
-
1
deal_catalogue = create(:deal_catalogue, deal: @deal, seller: @account)
-
-
1
delete :destroy, params: { token: @token, deal_id: @deal.id, id: @deal_catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(BxBlockCatalogue::DealCatalogue.find_by(id: @deal_catalogue.id)).to be_nil
-
1
expect(JSON.parse(response.body)["message"]).to include("Deal Catalogue has been removed")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::DealsController, type: :controller do
-
1
before do
-
3
@account = FactoryBot.create(:account)
-
3
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
3
@deal = create(:deal,status: true)
-
end
-
-
1
describe "GET #index" do
-
1
it "returns a list of active deals" do
-
1
get :index, params: { token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
# expect(JSON.parse(response.body)["data"].size).to eq(BxBlockCatalogue::Deal.active_deals.count)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
context "when deal exists" do
-
1
it "returns the deal" do
-
1
get :show, params: { token: @token, id: @deal.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@deal.id.to_s)
-
end
-
end
-
-
1
context "when deal does not exist" do
-
1
it "returns a not found message" do
-
1
non_existent_id = 999
-
-
1
get :show, params: { token: @token, id: non_existent_id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Deal not available")
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::GatedBrandsController, type: :controller do
-
-
1
before do
-
4
@account = FactoryBot.create(:account)
-
4
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
4
@brand = create("brand")
-
4
@gated_brand = create(:gated_brand, brand: @brand)
-
end
-
-
1
let(:valid_attributes) {
-
1
{token: @token, brand_id: @brand.id, approved: true, reseller_permit_document: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf")) }
-
}
-
-
1
let(:invalid_attributes) {
-
1
{token: @token, brand_id: 999, approved: true, reseller_permit_document: nil }
-
}
-
-
1
describe 'GET #index' do
-
1
it 'returns a success response index' do
-
1
get :index, params: {brand_id: @brand.id}
-
1
expect(response).to be_successful
-
1
expect(response.body).to include(@gated_brand.brand_id.to_s)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success response show' do
-
1
get :show, params: { id: @gated_brand.id, brand_id: @brand.id }
-
1
expect(response).to be_successful
-
1
expect(response.body).to include(@gated_brand.approved.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("reseller_permit_document")
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'with valid params' do
-
1
it 'creates a new GatedBrand' do
-
1
expect {
-
1
post :create, params: valid_attributes
-
}.to change(BxBlockCatalogue::GatedBrand, :count).by(1)
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'with invalid params' do
-
1
it 'returns unprocessable entity status' do
-
1
post :create, params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq("Brand must exist")
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::HelpfulReviewsController, type: :controller do
-
1
let(:account) { create(:account, user_type: 'buyer') }
-
6
let(:account2) { create(:account, user_type: 'buyer') }
-
5
let(:token) { BuilderJsonWebToken.encode(account2.id, token_type: 'login') }
-
2
let(:token1) { BuilderJsonWebToken.encode(0, token_type: 'login') }
-
6
let(:review) { create(:review) }
-
4
let(:helpful_review) { create(:helpful_review, review: review, customer: account2) }
-
-
1
describe 'POST #create' do
-
1
context 'when marking a review as helpful' do
-
1
it 'creates a new HelpfulReview record' do
-
1
post :create, params: { review_id: review.id, token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to eq('Marked as helpful')
-
end
-
-
1
it 'returns an error when the HelpfulReview cannot be saved' do
-
1
post :create, params: { review_id: review.id, token: token }
-
1
post :create, params: { review_id: review.id, token: token }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['error']).to eq('Could not mark as helpful')
-
end
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
context 'when unmarking a review as helpful' do
-
1
before do
-
3
helpful_review
-
end
-
-
1
it 'removes the HelpfulReview record' do
-
-
1
delete :destroy, params: { review_id: review.id, token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to eq('Unmarked as helpful')
-
end
-
-
1
it 'returns an error if there is no HelpfulReview record to destroy' do
-
1
delete :destroy, params: { review_id: review.id, token: token }
-
1
delete :destroy, params: { review_id: review.id, token: token }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['error']).to eq('Could not unmark as helpful')
-
end
-
-
1
it 'returns an error if account not found' do
-
1
delete :destroy, params: { review_id: review.id, token: token1 }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['message']).to eq("Account does not exist")
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::ParentCataloguesController, type: :controller do
-
-
1
account = FactoryBot.create(:account)
-
1
token = BuilderJsonWebToken.encode(account.id, token_type: 'login')
-
1
category = FactoryBot.create(:category)
-
1
brand = FactoryBot.create(:brand)
-
1
parent_catalogue = FactoryBot.create(:parent_catalogue, category: category,brand: brand )
-
1
catalogue = FactoryBot.create(:catalogue, category: category, brand: brand, parent_catalogue: parent_catalogue)
-
-
1
describe 'get search_parent_catalogues_by_title_or_brand_name' do
-
-
1
context 'when product and brand are provided' do
-
1
it 'returns matching catalogues for product and brand' do
-
1
get :search_parent_catalogues_by_title_or_brand_name, params: { token: token,product_keyword: parent_catalogue.product_title, brand_keyword: brand.brand_name }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['id']).to eq(parent_catalogue.id.to_s)
-
end
-
end
-
-
1
context 'when only product keyword is provided' do
-
1
it 'returns matching catalogues based on the product' do
-
1
get :search_parent_catalogues_by_title_or_brand_name, params: { token: token, brand_keyword: brand.brand_name }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['brand']['brand_name']).to include(brand.brand_name)
-
end
-
end
-
-
1
context 'when no matching products or brands are found' do
-
1
it 'returns a not found message' do
-
1
post :search_parent_catalogues_by_title_or_brand_name, params: { token: token, product_keyword: 'Product3' }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['message']).to eq('No products found')
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::ProductContentsController, type: :controller do
-
-
1
before do
-
7
@account = FactoryBot.create(:account)
-
7
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@category = FactoryBot.create(:category)
-
7
@sub_category = FactoryBot.create(:sub_category)
-
7
@mini_category = FactoryBot.create(:mini_category)
-
7
@micro_category = FactoryBot.create(:micro_category)
-
-
7
@custom_field1 = FactoryBot.create(:custom_field, field_name: 'Field1', fieldable: @category)
-
7
@custom_field2 = FactoryBot.create(:custom_field, field_name: 'Field2', fieldable: @sub_category)
-
7
@custom_field3 = FactoryBot.create(:custom_field, field_name: 'Field3', fieldable: @mini_category)
-
7
@custom_field4 = FactoryBot.create(:custom_field, field_name: 'Field4', fieldable: @micro_category)
-
-
7
@catalogue = create(:catalogue, category: @category, sub_category: @sub_category, mini_category: @mini_category, micro_category: @micro_category)
-
7
@catalogue_content = @catalogue.catalogue_contents.last
-
-
7
@product_content = create(:product_content, catalogue: @catalogue)
-
7
@image_urls = create_list(:image_url,2, product_content: @product_content)
-
7
@image_urls = create_list(:image_url,2, product_content: @product_content)
-
-
7
@deal = create(:deal, status: true)
-
7
@deal_catalogue = create(:deal_catalogue, deal: @deal, catalogue: @catalogue, seller: @account)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success response' do
-
1
get :index, params: { catalogue_id: @catalogue.id, token: @token }
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
let(:valid_params) do
-
{
-
2
"data": {
-
"attributes": {
-
"gtin": Faker::Number.number(digits: 9),
-
"unique_psku": @catalogue.sku,
-
"brand_name": "Brand Name",
-
"product_title": "Product Title",
-
"mrp": 150.00,
-
"retail_price": 129.99,
-
"long_description": "Product long description",
-
"whats_in_the_package": "Package content",
-
"country_of_origin": "India",
-
"product_color": "Grey",
-
"dispenser_type": "Type",
-
"scent_type": "Scent",
-
"target_use": "Target use",
-
"style_name": "Style Name",
-
"size_and_capacity_attributes": {
-
"size": 2,
-
"size_unit": "Millimeter",
-
"hs_code": "123475",
-
"prod_model_name": "XYZ",
-
"capacity": 3,
-
"capacity_unit": "Millilitre",
-
"prod_model_number": "123ABC123",
-
"number_of_pieces": 10
-
},
-
"shipping_detail_attributes": {
-
"shipping_length": 5,
-
"shipping_length_unit": "Gram",
-
"shipping_height": 3,
-
"shipping_height_unit": "Gram",
-
"shipping_width": 2,
-
"shipping_width_unit": "Gram",
-
"shipping_weight": 1.5,
-
"shipping_weight_unit": "Kilogram"
-
},
-
"image_urls_attributes": [
-
{
-
"url": "https://example.com/image1.jpg"
-
},
-
{
-
"url": "https://example.com/image2.jpg"
-
}
-
],
-
"feature_bullets_attributes": [
-
{
-
"field_name": "feature_bullet_1",
-
"value": "Bullet 1"
-
},
-
{
-
"field_name": "feature_bullet_2",
-
"value": "Bullet 2"
-
}
-
],
-
"special_features_attributes": [
-
{
-
"field_name": "special_feature_1",
-
"value": "Special Feature 1"
-
},
-
{
-
"field_name": "special_feature_2",
-
"value": "Special Feature 2"
-
}
-
],
-
catalogue_content_attributes: [
-
{
-
id: @catalogue_content.id,
-
value: "Updated Value"
-
}
-
]
-
}
-
}
-
}
-
end
-
-
1
it 'creates a new ProductContent' do
-
1
post :create, params: valid_params.merge(catalogue_id: @catalogue.id, token: @token)
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)['data']['attributes']['brand_name']).to eq("Brand Name")
-
end
-
-
1
it 'updates the catalogue content' do
-
1
post :create, params: valid_params.merge(catalogue_id: @catalogue.id, token: @token)
-
1
@catalogue_content.reload
-
1
expect(@catalogue_content.value).to eq("Updated Value")
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
let(:valid_params) do
-
{
-
2
data: {
-
attributes: {
-
retail_price: 199.99,
-
"image_urls_attributes": [
-
{
-
id: @product_content.image_urls.first.id,
-
"url": "https://example.com/image3.jpg"
-
},
-
{
-
id: @product_content.image_urls.last.id,
-
"url": "https://example.com/image4.jpg",
-
_destroy: true
-
}
-
]
-
}
-
}
-
}
-
end
-
-
1
let(:mer_param) do
-
2
{ catalogue_id: @catalogue.id, id: @product_content.id, token: @token }
-
end
-
-
1
it 'updates the update_associated_content' do
-
1
patch :update, params: valid_params.merge(mer_param)
-
1
@product_content.reload
-
1
expect(@product_content.retail_price).to eq(valid_params[:data][:attributes][:retail_price])
-
1
expect(@deal_catalogue.reload.seller_price).to eq(valid_params[:data][:attributes][:retail_price])
-
1
expect(response).to be_successful
-
end
-
-
1
it 'delete the requested product_content' do
-
1
patch :update, params: valid_params.merge(mer_param)
-
1
@product_content.reload
-
1
expect(@product_content.image_urls.count).to eq(4)
-
# expect(response).to be_successful
-
end
-
-
end
-
-
1
describe 'Error response' do
-
1
it 'returns the correct error messages for blank fields' do
-
1
post :create, params: {
-
data: {
-
attributes: {
-
gtin: @product_content.gtin,
-
unique_psku: @product_content.unique_psku,
-
brand_name: '',
-
product_title: '',
-
mrp: 150.00,
-
retail_price: 129.99
-
}
-
},
-
catalogue_id: @catalogue.id,
-
token: @token
-
}
-
1
response_body = JSON.parse(response.body)
-
1
expect(response_body['errors']).to match_array([
-
"Brand name can't be blank",
-
"Product title can't be blank"
-
])
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
-
1
it 'returns the correct error messages for existing product' do
-
1
@catalogue_2 = create(:catalogue)
-
1
@product_content_2 = create(:product_content, catalogue: @catalogue_2)
-
1
post :update, params: {
-
data: {
-
attributes: {
-
gtin: @product_content.gtin,
-
unique_psku: @product_content.unique_psku,
-
brand_name: 'Brand',
-
product_title: 'Title',
-
mrp: 150.00,
-
retail_price: 129.99
-
}
-
},
-
catalogue_id: @catalogue_2.id,
-
token: @token,
-
id: @product_content_2.id
-
}
-
1
response_body = JSON.parse(response.body)
-
1
expect(response_body['errors']).to match_array([
-
"Gtin has already been taken",
-
"Unique psku must match the SKU of the associated catalogue"
-
])
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::ProductVariantGroupsController, type: :controller do
-
-
1
before do
-
7
@account = FactoryBot.create(:account, user_type: 'seller')
-
7
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@catalogue = create(:catalogue)
-
7
@product_content = create(:product_content, catalogue: @catalogue)
-
7
@catalogue_variant = create(:catalogue_variant, seller: @account)
-
7
@product_variant_group = create(:product_variant_group, catalogue: @catalogue)
-
7
@group_attributes = create_list(:group_attribute, 2, product_variant_group: @product_variant_group)
-
7
@error_msg = "Product sku can't be blank"
-
end
-
-
1
let(:valid_params) do
-
{
-
1
_json: [
-
{
-
catalogue_variant_id: @catalogue_variant.id,
-
product_sku: 'ABC123',
-
group_attributes_attributes: [
-
{ attribute_name: 'Memory', option: '128' },
-
{ attribute_name: 'Size', option: 'Large' }
-
]
-
},
-
{
-
catalogue_variant_id: @catalogue_variant.id,
-
product_sku: 'ABC2123',
-
group_attributes_attributes: [
-
{ attribute_name: 'Color', option: 'Red' },
-
{ attribute_name: 'Ram', option: '8' }
-
]
-
}
-
]
-
}
-
end
-
-
1
describe 'POST #create' do
-
1
it 'creates a new product variant group' do
-
1
post :create, params: valid_params.merge({catalogue_id: @catalogue.id,token: @token})
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it 'returns errors for invalid params' do
-
1
post :create, params: {token: @token, catalogue_id: @catalogue.id, _json: [{catalogue_variant_id: @catalogue_variant.id, product_sku: '',group_attributes_attributes: [{ attribute_name: 'attr', option: 'value' }] }] }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors']).to include("sku can't be blank")
-
end
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a list of product variant groups' do
-
1
get :index, params: { catalogue_id: @catalogue.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"][0]["id"]).to eq(@product_variant_group.id.to_s)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns the details of a product variant group' do
-
1
get :show, params: { catalogue_id: @catalogue.id, id: @product_variant_group.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@product_variant_group.id.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]['product_bibc']).to eq(@product_variant_group.product_bibc)
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
it 'updates the product variant group' do
-
1
put :update, params: {token: @token, catalogue_id: @catalogue.id, id: @product_variant_group.id, product_sku: 'UpdatedSKU' }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(@product_variant_group.reload.product_sku).to eq('UpdatedSKU')
-
end
-
-
1
it 'returns errors for invalid params :update' do
-
1
put :update, params: {token: @token, catalogue_id: @catalogue.id, id: @product_variant_group.id, product_sku: '' }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors']).to include(@error_msg)
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the product variant group' do
-
1
delete :destroy, params: {token: @token, catalogue_id: @catalogue.id, id: @product_variant_group.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to include("Product variant Destroyed")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::RestrictedBrandsController, type: :controller do
-
-
1
before do
-
7
@account = FactoryBot.create(:account, user_type: "seller")
-
7
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@brand = create("brand")
-
7
@restricted_brand = create(:restricted_brand, brand: @brand, seller: @account)
-
end
-
-
1
let(:valid_attributes) {
-
2
{token: @token, brand_id: @brand.id, approved: true, reseller_permit_document: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf")) }
-
}
-
-
1
let(:invalid_attributes) {
-
2
{token: @token, brand_id: 999, approved: true }
-
}
-
-
1
describe 'GET #index' do
-
1
it 'returns a success response index' do
-
1
get :index, params: {brand_id: @brand.id, token: @token}
-
1
expect(response).to be_successful
-
1
expect(response.body).to include(@restricted_brand.brand_id.to_s)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success response show' do
-
1
get :show, params: { id: @restricted_brand.id, brand_id: @brand.id, token: @token }
-
1
expect(response).to be_successful
-
1
expect(response.body).to include(@restricted_brand.approved.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("reseller_permit_document")
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'with valid params' do
-
1
it 'creates a new RestrictedBrand' do
-
1
expect {
-
1
post :create, params: valid_attributes
-
}.to change(BxBlockCatalogue::RestrictedBrand, :count).by(1)
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'with invalid params' do
-
1
it 'returns unprocessable entity status' do
-
1
post :create, params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq("Brand must exist")
-
end
-
end
-
end
-
-
1
describe 'Patch #update' do
-
1
context 'update with valid params' do
-
1
it 'update a new RestrictedBrand' do
-
1
patch :update, params: valid_attributes.merge(id: @restricted_brand.id)
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context 'update with invalid params' do
-
1
it 'returns unprocessable entity status update' do
-
1
patch :update, params: invalid_attributes.merge(id: @restricted_brand.id)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
# expect(JSON.parse(response.body)['errors'][0]).to eq("Brand must exist")
-
end
-
end
-
end
-
-
1
describe 'Delete #destroy' do
-
1
context 'delete restricted_brand' do
-
1
it 'destroy RestrictedBrand' do
-
1
delete :destroy, params: {brand_id: @brand.id, id: @restricted_brand.id , token: @token}
-
1
expect(response).to have_http_status(:no_content)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::ReviewsController, type: :controller do
-
-
1
before do
-
21
@account = FactoryBot.create(:account, user_type: "buyer")
-
21
@seller = FactoryBot.create(:account, user_type: "seller")
-
21
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
21
@token_1 = BuilderJsonWebToken.encode(@seller.id, token_type: 'login')
-
21
@review = create(:review, is_approved: true)
-
21
@catalogue = create(:catalogue, seller: @seller )
-
21
@order_status = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'On Going')
-
21
@order = create(:shopping_cart_order, customer: @account, order_status: @order_status)
-
21
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
21
@review_1 = create(:review, account: @seller, rating: 3, review_type: 'seller', catalogue: @catalogue, is_approved: true, reviewer_id: @account.id, order_item_id: @order_item.id )
-
21
@review_2 = create(:review, account: @seller, rating: 4, review_type: 'delivery', catalogue: @catalogue, is_approved: true, reviewer_id: @account.id, order_item_id: @order_item.id )
-
-
end
-
-
-
1
let(:valid_params) {
-
2
{ product: { review_type: 'product', title: Faker::Lorem.paragraph, description: Faker::Lorem.paragraph(sentence_count: 3), rating: Faker::Number.between(from: 1, to: 5), catalogue_id: @catalogue.id, order_item_id: @order_item.id },token: @token }
-
}
-
-
1
describe "GET #index" do
-
1
it "return review listing" do
-
1
get :index, params: {token: @token, catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it "doesn't return review listing" do
-
1
get :index, params: {token: @token, catalogue_id: 0}
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Reviews not found with Catalogue id 0")
-
end
-
end
-
-
1
describe "POST #create" do
-
1
context "with valid params" do
-
1
it "creates a new review" do
-
1
expect {
-
1
post :create, params: valid_params
-
}.to change(BxBlockCatalogue::Review, :count).by(1)
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Review added successfully")
-
end
-
-
1
it "doesn't create a new review" do
-
1
valid_params[:product][:rating] = ''
-
1
post :create, params: valid_params
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors']).to eq(["Rating can't be blank", "Rating is not a number"])
-
end
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'show review' do
-
1
get :show, params: { token: @token , id: @review.id, is_approved: true}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it "doesn't return review" do
-
1
get :show, params: {token: @token, id: 0}
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Review with id 0 doesn't exists")
-
end
-
end
-
-
1
describe 'Delete #destroy' do
-
1
it 'destroy review' do
-
1
delete :destroy, params: { token: @token , id: @review.id, is_approved: true}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Review destroyed successfully")
-
end
-
end
-
-
1
describe 'GET #user_review_listing' do
-
1
context "return user review's listing" do
-
1
it 'renders a response with product reviews' do
-
1
@review.update(catalogue_id: @catalogue.id)
-
# @seller.review_and_ratings << @review_2
-
1
get :user_review_listing, params: { seller: { seller_id: @seller.id }, token: @token_1, catalogue_id: @catalogue.id, review_type: 'delivery' }
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'renders an invalid params response' do
-
1
get :user_review_listing, params: { token: @token, review_type: 'productt' }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe 'GET #seller_happiness_listing' do
-
1
context "return seller happiness listing" do
-
1
it "returns the seller happiness indicator" do
-
1
@seller.review_and_ratings << @review_1
-
1
@seller.review_and_ratings << @review_2
-
-
1
params = { filter_by: [3,4], token: @token_1 }
-
-
1
get :seller_happiness_indicator, params: params
-
-
1
expect(response).to have_http_status(:ok)
-
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response).to include('seller', 'delivery')
-
-
1
type1_data = json_response['seller']
-
1
expect(type1_data['meta']).to have_key('seller_review_percentages')
-
1
expect(type1_data['reviews']).to be_a(Array)
-
-
1
type2_data = json_response['delivery']
-
1
expect(type2_data['meta']).to have_key('average_rating')
-
1
expect(type2_data['reviews']).to be_a(Array)
-
end
-
-
1
it "returns the seller happiness indicator without filter" do
-
1
@seller.review_and_ratings << @review_1
-
-
1
get :seller_happiness_indicator, params: {token: @token_1 }
-
-
1
expect(response).to have_http_status(:ok)
-
-
1
json_response1 = JSON.parse(response.body)
-
1
expect(json_response1).to include('seller')
-
-
1
type1_data = json_response1['seller']
-
1
expect(type1_data['reviews'][0]).to have_key('review_images')
-
1
expect(type1_data['meta']).to have_key('seller_review_percentages')
-
1
expect(type1_data['reviews']).to be_a(Array)
-
end
-
-
1
it "returns a not_found response when no reviews are found" do
-
-
1
get :seller_happiness_indicator, params: { token: @token_1 }
-
-
1
expect(response).to have_http_status(:not_found)
-
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response).to include('message')
-
1
expect(json_response['message']).to eq("No reviews found for this seller")
-
end
-
end
-
end
-
-
1
describe "POST #update" do
-
1
context "update with valid params" do
-
1
before do
-
5
@update_params = {review: {title: "updated title", description: "updated desc"}}
-
end
-
1
it "update a new review" do
-
1
patch :update, params: @update_params.merge(id: @review_1.id, token: @token)
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@review_1.id.to_s)
-
end
-
-
1
it "doesn't update a new review" do
-
1
@update_params[:review][:rating] = ''
-
1
patch :update, params: @update_params.merge(id: @review_1.id, token: @token)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Rating can't be blank")
-
end
-
-
1
it "update a new review with helpful option" do
-
1
patch :update, params: @update_params.merge(id: @review_1.id, token: @token, helpful: true)
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["helpful_count"]).to eq(@review_1.helpful_count)
-
end
-
-
1
it "review not exist" do
-
1
patch :update, params: @update_params.merge(id: 00, token: @token)
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["errors"]).to eq("Review not found")
-
end
-
-
1
it "review image above 5 mb" do
-
1
patch :update, params: @update_params.merge(
-
id: @review_1.id,
-
token: @token,
-
review: { review_images: [fixture_file_upload(Rails.root.join('spec', 'fixtures', 'files', 'Sampleimage5mb.jpg'))] }
-
)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Review Failed to upload image. only png, jpg, jpeg format is allowed and maximum size is 5mb")
-
end
-
end
-
end
-
-
1
describe "GET #buyer_review_listing" do
-
1
before do
-
1
@buyer = FactoryBot.create(:account, user_type: "buyer")
-
1
@token_1 = BuilderJsonWebToken.encode(@buyer.id, token_type: 'login')
-
1
@catalogue_1 = create(:catalogue, seller: @seller)
-
1
@order_status_1 = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'On Going')
-
1
@order_1 = create(:shopping_cart_order, customer: @buyer, order_status: @order_status_1)
-
1
@order_item_1 = create(:shopping_cart_order_item, catalogue: @catalogue_1, order: @order_1)
-
1
@review_3 = create(:review, reviewer_id: @buyer.id, account_id: @seller.id, rating: 3, review_type: 'seller', catalogue: @catalogue_1, order_item_id: @order_item_1.id)
-
1
@order_item_1.reload
-
end
-
-
1
context "getting buyer reviews" do
-
1
it "success result from response" do
-
1
get :buyer_review_listing, params: {token: @token_1, order_item_id: @order_item_1.id}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['id']).to eq(@review_3.id.to_s)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['order_item']['id']).to eq(@order_item_1.id)
-
end
-
end
-
end
-
-
1
describe "GET #customer_rating_and_reviews" do
-
1
context "when review type is provided" do
-
1
it "returns the reviews of specific type" do
-
1
get :customer_rating_and_reviews, params: {catalogue_id: @catalogue.id, review_type: 'seller'}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['total_reviews']).to eq(@catalogue.review_and_ratings.where(review_type: 'seller').approved_reviews.count)
-
1
expect(JSON.parse(response.body)['reviews']['data'].first['attributes']['review_type']).to eq('seller')
-
end
-
end
-
-
1
context "when review type is not provided" do
-
1
it "returns the all reviews of catalogue" do
-
1
get :customer_rating_and_reviews, params: {catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['reviews']).to have_key('data')
-
end
-
end
-
-
1
context "when current account selected helpful" do
-
1
it "returns the all reviews of catalogue and helpful record" do
-
1
get :customer_rating_and_reviews, params: { catalogue_id: @catalogue.id, account_id: @account.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['reviews']['data'][0]["attributes"]).to have_key('helpful')
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::StoreFrontsController, type: :controller do
-
1
let(:valid_account_id) { 1 }
-
1
let(:invalid_account_id) { 999 }
-
1
let(:valid_category_id) { 1 }
-
1
before do
-
20
@account = FactoryBot.create(:account)
-
20
@account_b = FactoryBot.create(:account, user_type: 'buyer')
-
20
@account1 = FactoryBot.create(:account, user_type: "seller")
-
20
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
20
@token_1 = BuilderJsonWebToken.encode(@account1.id, token_type: 'login')
-
20
@category = FactoryBot.create(:category)
-
20
@brand = FactoryBot.create(:brand)
-
20
@catalogue = FactoryBot.create(:catalogue, category_id: @category.id, brand_id: @brand.id, seller_id: @account1.id, status: true)
-
20
@catalogue_without_review = FactoryBot.create(:catalogue, category_id: @category.id, brand_id: @brand.id, seller_id: @account1.id, status: true)
-
20
@review = FactoryBot.create(:review)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a list of latest product' do
-
1
get :latest_product, params: { token: @token, account_id: @account.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a list of seller catalogue' do
-
1
get :index, params: { token: @token, account_id: @account1.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
1
it 'return a list by category' do
-
1
get :index, params: { token: @token, account_id: @account1.id, category_id: @category.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #return by popular_product' do
-
1
it 'returns a list of popular products' do
-
1
get :popular_product, params: { token: @token, account_id: @account.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #average_rating_for_product' do
-
1
it 'returns average rating for a product' do
-
1
review = FactoryBot.create(:review, catalogue: @catalogue, rating: 4)
-
1
get :average_rating_for_product, params: { token: @token, account_id: @account.id, catalogue_id: @catalogue.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
1
it ' not found product' do
-
1
get :average_rating_for_product, params: { token: @token, account_id: @account.id, catalogue_id: 'invalid_id' }
-
1
expect(response).to have_http_status(:not_found)
-
end
-
-
1
it ' when reviews not product' do
-
1
get :average_rating_for_product, params: { token: @token, account_id: @account.id, catalogue_id: @catalogue_without_review.id }
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
-
1
describe 'GET #average_rating_for_seller' do
-
1
it 'returns the average rating for the seller' do
-
1
get :average_rating_for_seller, params: { token: @token, account_id: @account1.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #ratings_percentage' do
-
1
it 'returns the correct ratings percentage for the seller' do
-
1
review = FactoryBot.create(:review, account: @account1, rating: 4)
-
1
get :ratings_percentage, params: { token: @token, account_id: @account1.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #latest_review_for_seller' do
-
1
it 'returns the latest reviews for the seller' do
-
1
review_accountb = FactoryBot.create(:review, review_type: 'seller', reviewer_id: @account_b.id, account_id: @account1.id )
-
1
get :latest_review_for_seller, params: { token: @token_1, account_id: @account1.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['name']).to eq(@account1.full_name)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']['created_at']).to eq(@account1.created_at.strftime("%d/%m/%y"))
-
-
end
-
end
-
-
1
describe '#list_reviews GET' do
-
1
context 'when reviews not found' do
-
1
it 'not_found response' do
-
1
get :list_reviews, params: {catalogue_id: 0}
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
-
1
context 'when reviews present' do
-
1
it 'revert with a successful response' do
-
1
@review.update(catalogue_id: @catalogue.id)
-
1
get :list_reviews, params: {catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context 'when reviews with seller type' do
-
1
it 'returns a successful response with seller reviews' do
-
1
@review.update(catalogue_id: @catalogue.id, review_type: 'seller')
-
1
get :list_reviews, params: {catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context 'when reviews with product type' do
-
1
it 'return a successful response with product reviews' do
-
1
@review.update(catalogue_id: @catalogue.id, review_type: 'product')
-
1
get :list_reviews, params: {catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
end
-
-
1
describe '#ratings_percentage_for_product GET' do
-
1
context 'when product not found' do
-
1
it 'returns a not_found res' do
-
1
get :ratings_percentage_for_product, params: {catalogue_id: 0}
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
-
1
context 'when reviews are present there' do
-
1
it 'return a successful response' do
-
1
@review.update(catalogue_id: @catalogue.id)
-
1
get :ratings_percentage_for_product, params: {catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context 'when reviews are found' do
-
1
it 'returns a successful responses' do
-
1
get :ratings_percentage_for_product, params: {catalogue_id: @catalogue_without_review.id}
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
end
-
-
1
describe '#latest_review_for_product GET' do
-
1
context 'when product not found' do
-
1
it 'returns a not found response' do
-
1
get :latest_review_for_product, params: {catalogue_id: 0}
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
-
1
context 'when reviews are there' do
-
1
it 'returns successful response' do
-
1
@review.update(catalogue_id: @catalogue.id)
-
1
get :latest_review_for_product, params: {catalogue_id: @catalogue.id}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context 'when reviews found' do
-
1
it 'returns a not found response' do
-
1
get :latest_review_for_product, params: {catalogue_id: @catalogue_without_review.id}
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::WarehouseCataloguesController, type: :controller do
-
9
let(:account) { FactoryBot.create(:account, user_type: 'seller') }
-
9
let(:token) { BuilderJsonWebToken.encode(account.id, token_type: 'login') }
-
9
let(:warehouse) { FactoryBot.create(:warehouse, account: account) }
-
9
let(:catalogue) { FactoryBot.create(:catalogue, seller: account) }
-
1
let(:catalogue_2) { FactoryBot.create(:catalogue, seller: account) }
-
7
let(:product_variant_group) { FactoryBot.create(:product_variant_group, catalogue: catalogue) }
-
1
let(:group_attribute) {FactoryBot.create(:group_attribute, product_variant_group: product_variant_group)}
-
4
let(:warehouse_catalogue) { FactoryBot.create(:warehouse_catalogue,catalogue: catalogue, product_variant_group: product_variant_group, stocks: 12) }
-
-
1
describe 'POST create' do
-
1
it 'creates a new warehouse_catalogue' do
-
1
expect {
-
1
post :create, params: {token: token, warehouse_id: warehouse.id, warehouse_catalogue: { catalogue_id: catalogue.id, product_variant_group_id: product_variant_group.id, stocks: 100 } }
-
}.to change(BxBlockCatalogue::WarehouseCatalogue, :count).by(1)
-
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it 'renders errors if warehouse_catalogue creation fails' do
-
1
existing_warehouse_catalogue = warehouse.warehouse_catalogues.create(catalogue: catalogue, product_variant_group: product_variant_group)
-
-
1
post :create, params: {
-
token: token,
-
warehouse_id: warehouse.id,
-
warehouse_catalogue: {
-
catalogue_id: catalogue.id,
-
product_variant_group_id: product_variant_group.id,
-
stocks: 100
-
}
-
}
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include(
-
"This catalogue is already exist in this warehouse"
-
)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'returns the warehouse_catalogue' do
-
1
group_attribute = FactoryBot.create(:group_attribute, product_variant_group: product_variant_group)
-
1
warehouse_catalogue = FactoryBot.create(:warehouse_catalogue, warehouse: warehouse, catalogue: catalogue, product_variant_group: product_variant_group)
-
1
product_variant_group.group_attributes.reload
-
1
get :show, params: {token: token, warehouse_id: warehouse.id, id: warehouse_catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to eq(BxBlockCatalogue::WarehouseCatalogueSerializer.new(warehouse_catalogue).serializable_hash.to_json)
-
1
expect(JSON.parse(response.body)['data']['attributes']['selected_product_variant']['group_attributes'][0]).to have_key('attribute_name')
-
end
-
end
-
-
1
describe 'PUT update' do
-
1
it 'updates the warehouse_catalogue' do
-
1
put :update, params: {token: token, warehouse_id: warehouse.id, id: warehouse_catalogue.id, warehouse_catalogue: { stocks: 200 } }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(warehouse_catalogue.reload.stocks).to eq(200)
-
end
-
-
1
it 'error updates the warehouse_catalogue' do
-
1
put :update, params: {token: token, warehouse_id: warehouse.id, id: warehouse_catalogue.id, warehouse_catalogue: { stocks: 201, catalogue_id: "" } }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include(
-
"Catalogue must exist"
-
)
-
end
-
end
-
-
1
describe 'DELETE destroy' do
-
1
it 'deletes the warehouse_catalogue' do
-
1
delete :destroy, params: {token: token, warehouse_id: warehouse.id, id: warehouse_catalogue.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to eq("Warehouse catalogue deleted successfully")
-
end
-
end
-
-
1
describe 'GET index' do
-
1
before do
-
2
@warcatalogue = FactoryBot.create(:warehouse_catalogue, warehouse: warehouse, catalogue: catalogue)
-
end
-
1
it 'returns all warehouse_catalogues for the warehouse' do
-
-
1
get :index, params: {token: token, warehouse_id: warehouse.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body).size).to eq(2)
-
end
-
-
1
it 'returns searched warehouse_catalogues for the warehouse' do
-
-
1
get :index, params: {token: token, warehouse_id: warehouse.id, search_query: @warcatalogue.catalogue.sku }
-
-
1
expect(JSON.parse(response.body)['data'][0]['id']).to eq(@warcatalogue.id.to_s)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::WarehousesController, type: :controller do
-
-
1
before do
-
15
@account = FactoryBot.create(:account)
-
15
@account1 = FactoryBot.create(:account, user_type: "seller")
-
15
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
15
@token1 = BuilderJsonWebToken.encode(@account1.id, token_type: 'login')
-
15
@warehouse = create(:warehouse, account: @account1)
-
15
@catalogues = create_list(:catalogue, 3, seller: @account1)
-
15
@error = "{\"errors\":[{\"message\":\"You are not authorized to access warehouse\"}]}"
-
15
@user_authorization = "user not authorized"
-
end
-
-
1
let(:valid_params) {
-
4
{ warehouse: { warehouse_type: 'Type A', warehouse_name: 'Warehouse A' ,account_id: @account.id},token: @token }
-
}
-
-
1
describe "GET #index" do
-
1
it "returns a successful response" do
-
1
get :index, params: {token: @token}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it "returns warehouses in JSON format" do
-
1
get :index, params: {token: @token}
-
1
expect(response).to have_http_status(:ok)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response.last["warehouse_type"]).to eq(@warehouse.warehouse_type)
-
1
expect(json_response.last["warehouse_name"]).to eq(@warehouse.warehouse_name)
-
1
expect(json_response.last["warehouse_address_1"]).to eq(@warehouse.warehouse_address_1)
-
1
expect(json_response.last["contact_number"]).to eq(@warehouse.contact_number)
-
end
-
end
-
-
1
describe "POST #create" do
-
1
context "with valid params" do
-
1
it "creates a new warehouse" do
-
1
expect {
-
1
post :create, params: valid_params
-
}.to change(BxBlockCatalogue::Warehouse, :count).by(1)
-
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it "returns the created warehouse in JSON format" do
-
1
post :create, params: valid_params
-
1
expect(response).to have_http_status(:created)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response["warehouse_type"]).to eq(valid_params[:warehouse][:warehouse_type])
-
1
expect(json_response["warehouse_name"]).to eq(valid_params[:warehouse][:warehouse_name])
-
1
expect(json_response["warehouse_address_1"]).to eq(valid_params[:warehouse][:warehouse_address_1])
-
end
-
end
-
-
1
context "with invalid params" do
-
1
it "does not create a new warehouse" do
-
1
expect {
-
1
post :create, params: { warehouse: { warehouse_type: '' },token: @token }
-
}.to_not change(BxBlockCatalogue::Warehouse, :count)
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
-
end
-
end
-
-
1
describe 'GET #create_seller_warehouse' do
-
1
it @user_authorization do
-
1
get :seller_warehouse_listing, params:{ warehouse: {account_id: @account1.id}, token: @token }
-
1
expect(response).to have_http_status(:forbidden)
-
1
expect(response.body).to eq(@error)
-
end
-
-
1
it "seller's warehouse listing" do
-
1
warehouse = create(:warehouse, account: @account1)
-
1
catalogue = FactoryBot.create(:catalogue, seller: @account1)
-
1
product_variant_group = FactoryBot.create(:product_variant_group, catalogue: catalogue)
-
1
warehouse_catalogue = FactoryBot.create(:warehouse_catalogue,warehouse: warehouse, catalogue: catalogue, product_variant_group: product_variant_group, stocks: 12)
-
1
get :seller_warehouse_listing, params:{ warehouse: {account_id: @account1.id}, token: @token1 }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data'][0]['attributes']).to have_key('product_variant_groups')
-
end
-
end
-
-
1
describe 'POST #create_seller_warehouse' do
-
1
it @user_authorization do
-
1
post :create_seller_warehouse, params: valid_params
-
1
expect(response).to have_http_status(:forbidden)
-
1
expect(response.body).to eq(@error)
-
end
-
-
1
it "create seller's warehouse" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
post :create_seller_warehouse, params: valid_params
-
1
expect(response).to have_http_status(:created)
-
end
-
-
1
it "not create seller's warehouse" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
post :create_seller_warehouse, params: { warehouse: { account_id: @account.id, warehouse_name: "", warehouse_address_1: "new one"},token: @token }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to eq("{\"errors\":[\"Warehouse name can't be blank\"]}")
-
end
-
end
-
-
1
describe 'PUT #update_seller_warehouse' do
-
1
it @user_authorization do
-
1
put :update_seller_warehouse, params: { warehouse: { id: @warehouse.id, account_id: @account1.id, warehouse_name: "dummy", warehouse_address_1: "new one"}, token: @token }
-
1
expect(response).to have_http_status(:forbidden)
-
1
expect(response.body).to eq(@error)
-
end
-
-
1
it "update seller's warehouse" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
put :update_seller_warehouse, params: { warehouse: { id: @warehouse.id,account_id: @account.id, warehouse_name: "dummy", "catalogue_ids": @catalogues.map(&:id) }, token: @token }
-
1
@warehouse.reload
-
1
expect(response).to have_http_status(:ok)
-
1
expect(@warehouse).not_to be_nil
-
1
expect(@warehouse.warehouse_name).to eq("dummy")
-
1
expect(JSON.parse(response.body)["message"]["success"]).to eq(true)
-
end
-
-
# it "validation error on update" do
-
# # warehouse2 = create(:warehouse, account: @account1)
-
# # warehouse_catalogue = create(:warehouse_catalogue, warehouse: @warehouse, catalogue: @catalogues.last)
-
# put :update_seller_warehouse, params: { warehouse: { id: warehouse2.id, account_id: @account1.id, "catalogue_ids": @catalogues.map(&:id) }, token: @token1 }
-
# expect(response).to have_http_status(:ok)
-
# expect(JSON.parse(response.body)["message"]["success"]).to eq(false)
-
# end
-
-
1
it "not update seller's warehouse" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
1
put :update_seller_warehouse, params: { warehouse: { id: @warehouse.id, account_id: @account.id, warehouse_name: "", warehouse_type: ''}, token: @token }
-
1
@warehouse.reload
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to eq("{\"errors\":[\"Warehouse name can't be blank\"]}")
-
end
-
end
-
-
1
describe 'DELETE #delete_seller_warehouse' do
-
1
it @user_authorization do
-
1
delete :delete_seller_warehouse, params:{ warehouse: { id: @warehouse.id, account_id: @account1.id}, token: @token }
-
1
expect(response).to have_http_status(:forbidden)
-
1
expect(response.body).to eq(@error)
-
end
-
-
1
it "delete seller's warehouse" do
-
1
token = BuilderJsonWebToken.decode(@token)
-
1
AccountBlock::Account.find_by(id: token.id)&.update(user_type: 'seller')
-
-
1
expect {
-
1
delete :delete_seller_warehouse, params:{ warehouse: { id: @warehouse.id, account_id: @account1.id}, token: @token }
-
}.to change(BxBlockCatalogue::Warehouse, :count).by(-1)
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCategories::CategoriesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@category = create(:category)
-
end
-
-
1
describe "GET #index" do
-
1
it "returns a list of categories" do
-
-
1
get :index, params: {token: @token}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(BxBlockCategories::Category.count)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a single category" do
-
-
1
get :show, params: { token: @token,id: @category.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@category.id.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["name"]).to eq(@category.name)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("category_image")
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("header_image")
-
end
-
-
1
it "returns an error if category does not exist" do
-
1
non_existent_id = 0
-
-
1
get :show, params: { token: @token, id: non_existent_id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Category doesn't exists")
-
end
-
end
-
-
1
describe "GET #search_micro_categories" do
-
1
category_1 = FactoryBot.create(:category)
-
1
sub_category = FactoryBot.create(:sub_category, category: category_1)
-
1
mini_category = FactoryBot.create(:mini_category, sub_category: sub_category)
-
1
micro_category = FactoryBot.create(:micro_category, mini_category: mini_category)
-
1
it "returns a list of micro_categories" do
-
-
1
get :search_micro_categories, params: {search_query: micro_category.name}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"][0]["attributes"]["name"]).to eq(micro_category.name)
-
end
-
-
1
it "returns a list of micro_categories by category keyword" do
-
-
1
get :search_micro_categories, params: {search_query: category_1.name}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"][0]["attributes"]["category_id"]).to eq(category_1.id)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCategories::CustomFieldsController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
5
let(:category) { create(:category) }
-
2
let(:category_null) { create(:category) }
-
5
let!(:sub_category) { create(:sub_category, name: 'Test Subcategory', category: category) }
-
5
let!(:mini_category) { create(:mini_category, name: 'Test Mini Category', sub_category: sub_category) }
-
5
let!(:micro_category) { mini_category.micro_categories.create(name: 'Test Micro Category') }
-
5
let!(:custom_field_category) { create(:custom_field, fieldable: category) }
-
5
let!(:custom_field_micro_category) { create(:custom_field, fieldable: micro_category) }
-
-
1
describe 'GET index' do
-
1
it 'returns a list of custom fields' do
-
1
get :index, params: { category_id: category.id , token: @token}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(BxBlockCategories::CustomField.all.count)
-
end
-
end
-
-
1
describe 'GET show_custom_fields' do
-
1
context 'when category is present' do
-
1
it 'returns custom fields for the category' do
-
1
get :show_custom_fields, params: { category_id: category.id , token: @token}
-
1
expect(response).to have_http_status(:ok)
-
# expect(JSON.parse(response.body)["data"]).to include(custom_field_category.id.to_s)
-
# expect(JSON.parse(response.body)["data"]).to include(custom_field_category.name)
-
end
-
end
-
-
1
context 'when microcategory is present' do
-
1
it 'returns custom fields for the microcategory' do
-
1
get :show_custom_fields, params: { token: @token, category_id: category.id, micro_category_id: micro_category.id }
-
1
expect(response).to have_http_status(:ok)
-
# expect(JSON.parse(response.body)["data"]).to eq(custom_field_micro_category.id.to_s)
-
# expect(JSON.parse(response.body)["data"]).to eq(custom_field_micro_category.name)
-
end
-
end
-
-
1
context 'when neither category nor microcategory is present' do
-
1
it 'returns not found' do
-
1
get :show_custom_fields, params: { category_id: category_null.id , token: @token}
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response.body).to include("Custom fields don't exist for this category or microcategory.")
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCategories::MicroCategoriesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@category = create(:category)
-
1
@sub_category = create(:sub_category,category: @category)
-
1
@mini_categories = create_list(:mini_category, 2, sub_category: @sub_category)
-
1
@micro_categories = create_list(:micro_category,2, mini_category: @mini_categories.first)
-
end
-
-
1
describe "GET #index" do
-
1
it "returns a list of micro categories" do
-
-
1
get :index, params: {token: @token,category_id: @category.id, sub_category_id: @sub_category.id, mini_category_id: @mini_categories.first}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(@mini_categories.first.micro_categories.count)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a single micro_category" do
-
-
1
get :show, params: { token: @token, category_id: @category.id, sub_category_id: @sub_category.id, mini_category_id: @mini_categories.first, id: @micro_categories.first.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@micro_categories.first.id.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["name"]).to eq(@micro_categories.first.name)
-
end
-
-
1
it "returns an error if micro_category does not exist" do
-
1
non_existent_id = 999
-
-
1
get :show, params: { token: @token,category_id: @category.id,sub_category_id: @sub_category.id, mini_category_id: @mini_categories.first, id: non_existent_id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("MicroCategory doesn't exists")
-
end
-
end
-
-
1
describe "GET #list_microcategories_by_minicategory_ids" do
-
1
it "returns a list of micro categories by mini categories" do
-
-
1
get :list_microcategories_by_minicategory_ids, params: {mini_category_ids: [@mini_categories.first.id]}
-
-
1
expect(JSON.parse(response.body)["data"].size).to eq(@mini_categories.first.micro_categories.count)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCategories::MiniCategoriesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@category = create(:category)
-
1
@sub_category = create(:sub_category,category: @category)
-
1
@mini_categories = create_list(:mini_category, 2, sub_category: @sub_category)
-
1
@micro_categories = create_list(:micro_category,2, mini_category: @mini_categories.first)
-
end
-
-
1
describe "GET #index" do
-
1
it "returns a list of mini categories" do
-
-
1
get :index, params: {token: @token,category_id: @category.id, sub_category_id: @sub_category.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(@sub_category.mini_categories.count)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a single mini_category" do
-
-
1
get :show, params: { token: @token, category_id: @category.id, sub_category_id: @sub_category.id, id: @mini_categories.first.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@mini_categories.first.id.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["name"]).to eq(@mini_categories.first.name)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["micro_categories"].first['id']).to eq(@micro_categories.first.id)
-
end
-
-
1
it "returns an error if mini_category does not exist" do
-
1
non_existent_id = 999
-
-
1
get :show, params: { token: @token,category_id: @category.id,sub_category_id: @sub_category.id, id: non_existent_id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("MiniCategory doesn't exists")
-
end
-
end
-
-
1
describe "GET #list_minicategories_by_subcategory_ids" do
-
1
it "returns a list of mini categories by sub categories" do
-
-
1
get :list_minicategories_by_subcategory_ids, params: {sub_category_ids: [@sub_category.id]}
-
-
1
expect(JSON.parse(response.body)["data"].size).to eq(@sub_category.mini_categories.count)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCategories::SubCategoriesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@category = create(:category)
-
1
@sub_category = create(:sub_category,category: @category)
-
1
@mini_categories = create_list(:mini_category, 2, sub_category: @sub_category)
-
1
@micro_categories = create_list(:micro_category,2, mini_category: @mini_categories.first)
-
end
-
-
1
describe "GET #index" do
-
1
it "returns a list of sub categories" do
-
-
1
get :index, params: {token: @token,category_id: @category.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(@category.sub_categories.count)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a single sub_category" do
-
-
1
get :show, params: { token: @token, category_id: @category.id, id: @sub_category.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["id"]).to eq(@sub_category.id.to_s)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["name"]).to eq(@sub_category.name)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["mini_categories"].first['id']).to eq(@mini_categories.first.id)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["mini_categories"].first['micro_categories'].first['id']).to eq(@micro_categories.first.id)
-
end
-
-
1
it "returns an error if sub_category does not exist" do
-
1
non_existent_id = 999
-
-
1
get :show, params: { token: @token,category_id: @category.id, id: non_existent_id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["message"]).to eq("SubCategory doesn't exists")
-
end
-
-
1
it "returns an error if category does not exist" do
-
1
non_existent_id_cat = 993
-
-
1
get :show, params: { token: @token,category_id: non_existent_id_cat, id: @sub_category.id }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["errors"][0]).to eq("Record not found")
-
end
-
end
-
-
1
describe "GET #list_sub_categories_from_catalogues" do
-
1
it "returns a list of list_sub_categories_from_catalogues" do
-
1
catalogue = FactoryBot.create(:catalogue, category: @category, sub_category: @sub_category, status: true)
-
1
deal = FactoryBot.create(:deal)
-
1
deal_catalogue = FactoryBot.create(:deal_catalogue, deal: deal, catalogue: catalogue, seller: @account, status: 'approved' )
-
-
1
get :list_sub_categories_from_catalogues, params: {deal_id: deal.id}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"].size).to eq(1)
-
1
expect(JSON.parse(response.body)["data"][0]['id']).to eq(@sub_category.id.to_s)
-
end
-
-
1
it "error message list_sub_categories_from_catalogues" do
-
-
1
get :list_sub_categories_from_catalogues, params: {deal_id: nil}
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)["error"]).to eq("Deal not found")
-
end
-
end
-
-
1
describe "GET #list_subcategories_by_category_ids" do
-
1
it "returns a list of sub categories by category" do
-
-
1
get :list_subcategories_by_category_ids, params: {category_ids: [@category.id]}
-
-
1
expect(JSON.parse(response.body)["data"].size).to eq(@category.sub_categories.count)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockContactUs::ContactsController, type: :controller do
-
-
-
1
describe 'POST#Create contact' do
-
1
context 'Create Contact' do
-
1
it 'should create contact' do
-
1
expect {
-
1
post :create, params: {email: "test@gmail.com", description: "test", title: 'dummy', contact_type: "complaint", image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))}
-
}.to change(BxBlockContactUs::Contact, :count).by(1)
-
1
expect(response).to have_http_status :created
-
1
parsed_response_2 = JSON.parse(response.body)
-
1
expect(parsed_response_2['data']['attributes']).to have_key('image')
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
-
1
it 'should not create contact' do
-
1
post :create, params: {email: " "}
-
1
expect(response.body).to eq("{\"errors\":[{\"contact\":[\"Title can't be blank\",\"Email can't be blank\",\"Contact type can't be blank\",\"Description can't be blank\"]}]}")
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
1
RSpec.describe BxBlockCouponCg::CouponCodesController, type: :controller do
-
-
2
let (:coupon) {create(:coupon)}
-
4
let(:account) { FactoryBot.create(:account, user_type: 'seller') }
-
1
before(:each) do
-
3
@token = BuilderJsonWebToken.encode(account.id)
-
end
-
-
1
describe 'GET#Coupon Listing' do
-
1
context 'list of active coupons' do
-
1
it 'should return active coupons' do
-
1
get :index, params: { token: @token }
-
1
expect(response).to have_http_status :ok
-
end
-
end
-
end
-
-
1
describe 'GET# Show Coupon' do
-
1
context 'Show active coupon' do
-
1
it 'should show active coupon' do
-
1
get :show, params: { token: @token, id: coupon.id }
-
1
expect(response).to have_http_status :ok
-
end
-
-
1
it 'should not show active coupon' do
-
1
get :show, params: { token: @token, id: 0 }
-
1
expect(response).to have_http_status :not_found
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
1
RSpec.describe BxBlockCouponCg::SubscribeCouponsController, type: :controller do
-
-
4
let (:coupon) {create(:coupon)}
-
4
let (:catalogue) {create(:catalogue)}
-
6
let(:account) { FactoryBot.create(:account, user_type: 'seller') }
-
3
let (:subscribe_coupon) { FactoryBot.create(:subscribe_coupon, account_id: account.id, catalogue_id: catalogue.id, coupon_code_id: coupon.id) }
-
-
1
before(:each) do
-
5
@token = BuilderJsonWebToken.encode(account.id)
-
end
-
-
1
describe 'GET#Subscribe Coupon Listing' do
-
1
context 'list of subscribe coupons' do
-
1
it 'should return subscribe coupons' do
-
1
get :index, params: { token: @token }
-
1
expect(response).to have_http_status :ok
-
end
-
end
-
end
-
-
1
describe 'POST#Subscribe coupon' do
-
1
context 'Subscribe coupon' do
-
1
it 'should subscribe coupon' do
-
1
get :create, params: { token: @token, catalogue_id: catalogue.id, coupon_code_id: coupon.id }
-
1
expect(response).to have_http_status :created
-
end
-
-
1
it 'should not subscribe coupon' do
-
1
get :create, params: { token: @token, coupon_code_id: 0 }
-
1
expect(response).to have_http_status :unprocessable_entity
-
end
-
end
-
end
-
-
1
describe 'PUT#Subscribe coupon' do
-
1
context 'update subscribe coupon' do
-
1
it 'should update subscribe coupon' do
-
1
put :update, params: { token: @token, id: subscribe_coupon.id, catalogue_id: catalogue.id, coupon_code_id: coupon.id }
-
1
expect(response).to have_http_status :ok
-
end
-
end
-
end
-
-
1
describe 'DELETE#Subscribe coupon' do
-
1
context 'delete subscribe coupon' do
-
1
it 'should delete subscribe coupon' do
-
1
delete :destroy, params: { token: @token, id: subscribe_coupon.id }
-
1
expect(response).to have_http_status :ok
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCustomAds::AdvertisementsController, type: :controller do
-
1
before do
-
3
@advertisement = create(:advertisement, status: 1)
-
end
-
-
1
describe 'GET index' do
-
1
it 'returns a list of active advertisements' do
-
1
get :index
-
1
expect(response).to have_http_status(:success)
-
1
expect(JSON.parse(response.body)['message']).to eq('Successfully loaded')
-
1
expect(JSON.parse(response.body)['advertisements']).not_to be_empty
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'shows details of a specific advertisement' do
-
1
get :show, params: { id: @advertisement.id }
-
1
expect(response).to have_http_status(:success)
-
1
expect(JSON.parse(response.body)['message']).to eq('Successfully loaded')
-
1
expect(JSON.parse(response.body)['advertisement']['id']).to eq(@advertisement.id)
-
end
-
-
1
it 'returns an error if the advertisement does not exist' do
-
1
get :show, params: { id: 'invalid_id' }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq('Record not found')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::AuthorFavoriteBooksController, type: :controller do
-
-
1
before do
-
4
@seller = create(:account, user_type: 'seller')
-
4
@catalogues = create_list(:catalogue,8, seller: @seller)
-
4
@favorite_book_catalogues_attributes = @catalogues.map do |catalogue|
-
32
{ catalogue_id: catalogue.id }
-
end
-
4
@author_favorite_book = create(:author_favorite_book, title: 'Title1', status: true, favorite_book_catalogues_attributes: @favorite_book_catalogues_attributes)
-
4
@params_tp = {title: 'Title1', favorite_book_catalogues_attributes: @favorite_book_catalogues_attributes}
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a successful response with a list of fav book' do
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockDashboard::AuthorFavoriteBook.all.count)
-
end
-
-
1
it 'returns a successful response with a list of fav book filter' do
-
1
author_favorite_book_inx = create(:author_favorite_book, title: 'Title1', favorite_book_catalogues_attributes: @favorite_book_catalogues_attributes)
-
1
get :index, params: {title_contains: 'title2'}
-
-
1
parsed_response_1 = JSON.parse(response.body)
-
1
expect(parsed_response_1['data'][0]['attributes']['title']).to eq(author_favorite_book_inx.title)
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'returns a successful response with the details of a fav book' do
-
1
get :show, params: { id: @author_favorite_book.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response_2 = JSON.parse(response.body)
-
1
expect(parsed_response_2['data']['id']).to eq(@author_favorite_book.id.to_s)
-
end
-
-
end
-
-
1
describe 'GET #latest_author_favorite' do
-
-
1
it 'returns a successful response with the details of latest fav book' do
-
1
get :latest_author_favorite
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response_3 = JSON.parse(response.body)
-
1
expect(parsed_response_3['data']['id']).to eq(@author_favorite_book.id.to_s)
-
end
-
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::BannersController, type: :controller do
-
-
1
before do
-
7
BxBlockDashboard::BannerGroup.all.delete_all
-
7
@category = create(:category)
-
7
@subcategory = create(:sub_category, category: @category)
-
7
@catalogue = create(:catalogue)
-
7
@deal = create(:deal)
-
7
@banner_group = create(:banner_group, group_name: 'middle_group_2')
-
7
@banner_header = create(:banner, category: @category )
-
7
@banner_group_1 = BxBlockDashboard::BannerGroup.find_or_create_by(group_name: 'middle_group_1')
-
7
@single_image_type = 'single_image'
-
end
-
-
1
describe 'GET #header_slideshow_index' do
-
1
it 'returns a successful response header_slideshow_index' do
-
1
get :header_slideshow_index
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(@banner_header.title)
-
1
expect(response.body).to include(@banner_header.description)
-
1
expect(JSON.parse(response.body)["data"].last["attributes"]).to have_key("banner_image")
-
end
-
end
-
-
1
describe 'GET #header_single_images_index' do
-
1
it 'returns a successful response header_single_images_index' do
-
1
banner_header_2 = create(:banner, catalogue: @catalogue , banner_type: @single_image_type)
-
1
get :header_single_images_index
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(banner_header_2.title)
-
1
expect(response.body).to include(banner_header_2.description)
-
end
-
end
-
-
1
describe 'GET #middle_slideshow_index' do
-
1
context 'with a valid group_name' do
-
1
it 'returns a successful response middle_slideshow_index' do
-
1
banner_middle_1 = create(:banner, section: 'middle', sub_category: @subcategory, banner_group: @banner_group_1)
-
1
get :middle_slideshow_index, params: { group_name: 'middle_group_1' }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(banner_middle_1.title)
-
1
expect(response.body).to include(banner_middle_1.description)
-
end
-
end
-
-
1
context 'with a missing group_name' do
-
1
it 'returns a not found response' do
-
1
get :middle_slideshow_index
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response.body).to include('group_name params is missing')
-
end
-
end
-
end
-
-
1
describe 'GET #middle_single_images_index' do
-
1
it 'returns a successful response middle_single_images_index' do
-
1
banner_middle_2 = create(:banner, section: 'middle', deal: @deal, banner_type: @single_image_type, banner_group: nil)
-
-
1
get :middle_single_images_index
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(banner_middle_2.title)
-
1
expect(response.body).to include(banner_middle_2.description)
-
end
-
end
-
-
1
describe 'GET #footer_single_images_index' do
-
1
it 'returns a successful response footer_single_images_index' do
-
1
banner_footer = create(:banner, section: 'footer', category: @category, banner_type: @single_image_type)
-
-
1
get :footer_single_images_index
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response.body).to include(banner_footer.title)
-
1
expect(response.body).to include(banner_footer.description)
-
end
-
end
-
-
1
describe 'GET #top_banners' do
-
1
it 'returns a successful response top_banners' do
-
1
top_banner = BxBlockDashboard::Banner.find_or_create_by(title: "Free shipping on all UAE orders AED 200", button_text: "SHOP NOW",banner_type: "top_banner", button_link: "https://www.url.com", status: true)
-
-
1
get :top_banner
-
1
expect(response.body).to include(top_banner.title)
-
1
expect(response.body).to include(top_banner.button_text)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::GlobalSearchesController, type: :controller do
-
1
before do
-
21
@seller = FactoryBot.create(:account, user_type: 'seller')
-
21
@buyer = FactoryBot.create(:account, user_type: 'buyer')
-
21
@category = FactoryBot.create(:category)
-
21
@custom_field = FactoryBot.create(:custom_field, field_name: 'Old Field Name',fieldable: @category)
-
21
@brand = FactoryBot.create(:brand)
-
21
@subcategory = FactoryBot.create(:sub_category, category: @category)
-
21
@minicategory = FactoryBot.create(:mini_category, sub_category: @subcategory)
-
21
@microcategory = FactoryBot.create(:micro_category, mini_category: @minicategory)
-
21
@catalogue = FactoryBot.create(:catalogue, category: @category, sub_category: @subcategory, mini_category: @minicategory, micro_category: @microcategory, brand: @brand, status: true)
-
21
@product_content = FactoryBot.create(:product_content, catalogue: @catalogue, product_color: "grey", product_title: "stock product")
-
@search_keyword_bc = {
-
21
search_keyword: @catalogue.product_content.product_title,
-
}
-
21
@blank_keyword = { search_keyword: '' }
-
21
@no_result_keyword = { search_keyword: 'no_result_keyword' }
-
21
@no_result_found = 'No result found'
-
21
@rating = 4
-
21
@reviews = FactoryBot.create_list(:review, 3, reviewer_id: @buyer.id, catalogue: @catalogue, account_id: @seller.id, rating: @rating, review_type: 'product', is_approved: true)
-
21
@low_stock_prod = FactoryBot.create(:catalogue, category: @category,sub_category: @subcategory,mini_category: @minicategory, micro_category: @microcategory, brand: @brand, status: true, seller: @seller, stocks: 0)
-
21
@lsp_product_content = FactoryBot.create(:product_content, catalogue: @low_stock_prod, product_title: "low stock product", product_color: "grey")
-
21
@reviews = FactoryBot.create_list(:review, 3, reviewer_id: @buyer.id, catalogue: @low_stock_prod, account_id: @seller.id, rating: @rating, review_type: 'product', is_approved: true)
-
21
@low_stock_prod2 = FactoryBot.create(:catalogue, category: @category, sub_category: @subcategory, mini_category: @minicategory, micro_category: @microcategory, brand: @brand, stocks: nil, status: true)
-
21
@lsp_product_content2 = FactoryBot.create(:product_content, product_color: "grey", catalogue: @low_stock_prod2, product_title: "low stock product 2")
-
21
@reviews = FactoryBot.create_list(:review, 3, reviewer_id: @buyer.id, catalogue: @low_stock_prod2, account_id: @seller.id, rating: @rating, review_type: 'product', is_approved: true)
-
-
21
@catalogues = create_list(:catalogue, 6, seller: @seller, category: @category, sub_category: @subcategory, mini_category: @minicategory, micro_category: @microcategory, brand: @brand, status: true)
-
21
@product_content1 = FactoryBot.create(:product_content, catalogue: @catalogues.last, product_color: "grey", product_title: "stock product")
-
21
@trending_product_selections_attributes = @catalogues.map do |catalogue|
-
126
{ catalogue_id: catalogue.id }
-
end
-
21
@trending_product = create(:trending_product, slider: 1, trending_product_selections_attributes: @trending_product_selections_attributes)
-
21
@trending_slider = {trending_slider: 1}
-
end
-
-
1
describe 'GET #search' do
-
1
context 'with valid search keyword' do
-
1
let(:valid_keyword) do
-
{
-
9
"search_keyword": @catalogue.product_content.product_title,
-
"per_page": 50,
-
"page": 1,
-
"category_ids": [@category.id],
-
"sub_category_ids": [@subcategory.id],
-
"mini_category_ids": [@minicategory.id],
-
"micro_category_ids": [@microcategory.id],
-
"brand_ids": [@brand.id],
-
"min_price": 10,
-
"max_price": 500,
-
"sort_by": "whats_new",
-
"filter_by_rating": [@rating],
-
"color_filter": ["grey"],
-
"out_of_stocks": false
-
}
-
end
-
-
1
it 'renders search results' do
-
1
get :search, params: valid_keyword
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to eq('Successfully Loaded')
-
1
expect(response_body['min_range'].to_f).to be_a(Numeric)
-
1
expect(response_body['max_range'].to_f).to be_a(Numeric)
-
1
expect(response_body['total_count']).to be_an(Integer).or eq(nil)
-
-
1
expect(response_body['data'][2]['attributes']['product_content']['product_attributes']['product_title']).to eq(@catalogue.product_content.product_title)
-
1
expect(response_body['data'][0]['attributes']['status']).to eq(true)
-
1
expect(response_body['data'][2]['attributes']['stocks']).to eq(@catalogue.stocks)
-
1
expect(response_body['data'][1]['attributes']['stocks']).to eq(@low_stock_prod.stocks)
-
1
expect(response_body['data'][0]['attributes']['stocks']).to eq(@low_stock_prod2.stocks)
-
1
expect(response_body['data'][1]['attributes']['product_content']['product_attributes']['product_title']).to eq(@low_stock_prod.product_content.product_title)
-
1
expect(response_body['data'][1]['attributes']['final_price']).to eq(@low_stock_prod.final_price.to_s)
-
end
-
-
1
it 'renders search results with brand name' do
-
1
valid_keyword[:search_keyword] = @catalogue.brand.brand_name
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['brand']['brand_name']).to eq(@catalogue.brand.brand_name)
-
end
-
-
1
it 'renders search results with category name' do
-
1
valid_keyword[:search_keyword] = @catalogue.category.name
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['category']['name']).to eq(@catalogue.category.name)
-
end
-
-
1
it 'renders search results with subcategory name' do
-
1
valid_keyword[:search_keyword] = @catalogue.sub_category.name
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['sub_category']['name']).to eq(@catalogue.sub_category.name)
-
end
-
-
1
it 'renders search results with minicategory name' do
-
1
valid_keyword[:search_keyword] = @catalogue.mini_category.name
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['mini_category']['name']).to eq(@catalogue.mini_category.name)
-
end
-
-
1
it 'renders search results with microcategory name' do
-
1
valid_keyword[:search_keyword] = @catalogue.micro_category.name
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['micro_category']['name']).to eq(@catalogue.micro_category.name)
-
end
-
-
1
it 'renders search results with any one filter' do
-
-
1
valid_keyword[:category_ids] = nil
-
1
valid_keyword[:sub_category_ids] = nil
-
1
valid_keyword[:mini_category_ids] = nil
-
1
valid_keyword[:micro_category_ids] = nil
-
1
valid_keyword[:search_keyword] = @catalogue.brand.brand_name
-
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['brand']['id']).to eq(@catalogue.brand.id)
-
end
-
-
1
it 'renders search results with long description' do
-
1
valid_keyword[:search_keyword] = @product_content.long_description
-
1
get :search, params: valid_keyword
-
-
1
expect(response_body['data']).to be_empty
-
end
-
-
1
it 'filter by product color' do
-
1
post :search, params: valid_keyword
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['attributes']['product_content']['product_attributes']['product_color']).to eq(@catalogue.product_content.product_color)
-
end
-
-
1
it 'filter by out of stocks' do
-
-
1
valid_keyword_1 = { search_keyword: @low_stock_prod2.product_content.product_title, out_of_stocks: true }
-
-
1
post :search, params: valid_keyword_1
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['attributes']['stocks']).to eq(@low_stock_prod2.stocks)
-
end
-
-
1
it 'filters products by custom field values' do
-
1
custom_field_values = ['value1', 'value2']
-
1
catalogue_content1 = FactoryBot.create(:catalogue_content, catalogue: @catalogue, custom_field: @custom_field, value: custom_field_values.first)
-
1
catalogue_content2 = FactoryBot.create(:catalogue_content, catalogue: @catalogue, custom_field: @custom_field, value: custom_field_values.second)
-
-
1
post :search, params: { search_keyword: @catalogue.product_content.product_title, custom_field_values: custom_field_values }
-
-
1
expect(response).to have_http_status(:ok)
-
2
expect(JSON.parse(response.body)['data'].map { |item| item['id'] }).to include(@catalogue.id.to_s)
-
end
-
end
-
-
1
context 'with blank search keyword' do
-
-
1
it 'renders no product found' do
-
1
get :search, params: @blank_keyword
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response_body['message']).to eq('No products found')
-
end
-
end
-
-
1
context 'when no results match' do
-
1
it 'returns empty products list' do
-
1
get :search, params: @no_result_keyword
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']).to be_empty
-
end
-
end
-
end
-
-
1
describe 'GET #brands_filter_lists' do
-
1
context 'with valid search keyword for brands list' do
-
-
1
it 'renders brands filter list' do
-
1
get :brands_filter_lists, params: @search_keyword_bc
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['type']).to eq('brand')
-
end
-
-
1
it 'renders brands filter list by trending slider' do
-
1
get :brands_filter_lists, params: @trending_slider
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['id']).to eq(@catalogues.last.brand.id.to_s)
-
end
-
end
-
-
1
context 'with blank search keyword brands_filter_lists' do
-
1
it 'renders no result found brands_filter_lists' do
-
1
get :brands_filter_lists, params: @blank_keyword
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response_body['message']).to eq(@no_result_found)
-
end
-
-
1
it 'renders no result found brands_filter_lists by keyword' do
-
1
get :brands_filter_lists, params: @no_result_keyword
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response_body['message']).to eq(@no_result_found)
-
end
-
end
-
end
-
-
1
describe 'GET #categories_filter_lists' do
-
1
context 'with valid search keyword for category list' do
-
-
1
it 'renders categories filter list' do
-
1
get :categories_filter_lists, params: @search_keyword_bc
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'].last['type']).to eq('category')
-
end
-
-
1
it 'renders categories filter list by trending slider' do
-
1
get :categories_filter_lists, params: @trending_slider
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['id']).to eq(@catalogues.last.category.id.to_s)
-
end
-
end
-
-
1
context 'with blank search keyword categories_filter_lists' do
-
1
it 'renders no result found categories_filter_lists' do
-
1
get :categories_filter_lists, params: @blank_keyword
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response_body['message']).to eq(@no_result_found)
-
end
-
-
1
it 'renders no result found categories_filter_lists keyword' do
-
1
get :categories_filter_lists, params: @no_result_keyword
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response_body['message']).to eq(@no_result_found)
-
end
-
end
-
end
-
-
1
def response_body
-
30
JSON.parse(response.body)
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::HeaderCategoriesController, type: :controller do
-
-
1
before do
-
2
BxBlockDashboard::HeaderCategory.all.delete_all
-
2
@header_category = create(:header_category)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a successful response with a list of header categories' do
-
1
category_categories = create_list(:header_category, 3)
-
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockDashboard::HeaderCategory.all.count)
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'returns a successful response with the details of a header category' do
-
1
get :show, params: { id: @header_category.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data']['id']).to eq(@header_category.id.to_s)
-
1
expect(parsed_response['data']['attributes']['category']).to have_key("category_image")
-
1
expect(parsed_response['data']['attributes']['category']).to have_key("header_image")
-
1
expect(parsed_response['data']['attributes']['category']).to have_key("created_at")
-
1
expect(parsed_response['data']['attributes']['category']).to have_key("updated_at")
-
1
expect(parsed_response['data']['attributes']['category']).to have_key("created_at")
-
1
expect(parsed_response['data']['attributes']['category']['name']).to eq(@header_category.category.name)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::MostPopularCategoriesController, type: :controller do
-
-
1
before do
-
2
BxBlockDashboard::MostPopularCategory.all.delete_all
-
2
@popular_category = create(:most_popular_category)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a successful response with a list of popular categories' do
-
1
popular_categories = create_list(:most_popular_category, 3)
-
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockDashboard::MostPopularCategory.all.count)
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'returns a successful response with the details of a popular category' do
-
1
get :show, params: { id: @popular_category.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data']['id']).to eq(@popular_category.id.to_s)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::TopBrandsController, type: :controller do
-
-
1
before do
-
2
BxBlockDashboard::TopBrand.all.delete_all
-
2
@top_brand = create(:top_brand)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a successful response with a list of top brands' do
-
1
top_brands = create_list(:top_brand, 3)
-
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockDashboard::TopBrand.all.count)
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'returns a successful response with the details of a top brand' do
-
1
get :show, params: { id: @top_brand.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data']['id']).to eq(@top_brand.id.to_s)
-
end
-
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::TrendingProductsController, type: :controller do
-
-
1
before do
-
9
@seller = create(:account, user_type: 'seller')
-
9
@buyer = FactoryBot.create(:account, user_type: 'buyer')
-
9
@category = FactoryBot.create(:category)
-
9
@custom_field = FactoryBot.create(:custom_field, field_name: 'Old Field Name',fieldable: @category)
-
9
@brand = FactoryBot.create(:brand)
-
9
@subcategory = FactoryBot.create(:sub_category, category: @category)
-
9
@minicategory = FactoryBot.create(:mini_category, sub_category: @subcategory)
-
9
@microcategory = FactoryBot.create(:micro_category, mini_category: @minicategory)
-
-
9
@catalogues = create_list(:catalogue, 6, seller: @seller, category: @category, sub_category: @subcategory, mini_category: @minicategory, micro_category: @microcategory, brand: @brand, status: true)
-
9
@product_content = FactoryBot.create(:product_content, catalogue: @catalogues.last, product_color: "grey", product_title: "stock product")
-
9
@trending_product_selections_attributes = @catalogues.map do |catalogue|
-
54
{ catalogue_id: catalogue.id }
-
end
-
9
@trending_product = create(:trending_product, slider: 1, trending_product_selections_attributes: @trending_product_selections_attributes)
-
9
@catalogues.second.update(stocks: 0)
-
9
@product_content = FactoryBot.create(:product_content, catalogue: @catalogues.second, product_color: "grey", product_title: "low stock product")
-
-
9
@rating = 4
-
9
@reviews1 = FactoryBot.create_list(:review, 3, reviewer_id: @buyer.id, catalogue: @catalogues.last, account_id: @seller.id, rating: @rating, review_type: 'product', is_approved: true)
-
9
@reviews2 = FactoryBot.create_list(:review, 3, reviewer_id: @buyer.id, catalogue: @catalogues.second, account_id: @seller.id, rating: @rating, review_type: 'product', is_approved: true)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a successful response with a list of slider' do
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockDashboard::TrendingProduct.all.count)
-
end
-
-
1
it 'returns a successful response with a list of slider filter' do
-
1
trending_product_inx = create(:trending_product, slider: 'slider_2', trending_product_selections_attributes: @trending_product_selections_attributes)
-
1
get :index, params: {slider: 2}
-
-
1
parsed_response_1 = JSON.parse(response.body)
-
1
expect(parsed_response_1['data'][0]['attributes']['slider']).to eq(trending_product_inx.slider)
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'returns a successful response with the details of a slider' do
-
1
get :show, params: { id: @trending_product.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response_2 = JSON.parse(response.body)
-
1
expect(parsed_response_2['data']['id']).to eq(@trending_product.id.to_s)
-
end
-
end
-
-
1
describe 'GET #list_trending_products' do
-
1
context 'with valid slider keyword' do
-
1
let(:valid_keyword) do
-
{
-
3
"slider": 1,
-
"per_page": 50,
-
"page": 1,
-
"category_ids": [@category.id],
-
"sub_category_ids": [@subcategory.id],
-
"mini_category_ids": [@minicategory.id],
-
"micro_category_ids": [@microcategory.id],
-
"brand_ids": [@brand.id],
-
"min_price": 10,
-
"max_price": 500,
-
"sort_by": "whats_new",
-
"filter_by_rating": [@rating],
-
"color_filter": ["grey"],
-
"out_of_stocks": false
-
}
-
end
-
-
1
it 'renders slider results' do
-
1
post :list_trending_products, params: valid_keyword
-
-
1
expect(response_body['min_range'].to_f).to be_a(Numeric)
-
1
expect(response_body['max_range'].to_f).to be_a(Numeric)
-
1
expect(response_body['total_count']).to be_an(Integer).or eq(nil)
-
-
1
expect(response_body['data'][0]['attributes']['product_content']['product_attributes']['product_title']).to eq(@catalogues.last.product_content.product_title)
-
1
expect(response_body['data'][0]['attributes']['status']).to eq(true)
-
1
expect(response_body['data'][0]['attributes']['stocks']).to eq(@catalogues.last.stocks)
-
1
expect(response_body['data'][0]['attributes']['final_price']).to eq(@catalogues.last.final_price.to_s)
-
end
-
-
1
it 'filter by product color' do
-
1
post :list_trending_products, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['product_content']['product_attributes']['product_color']).to eq(@catalogues.last.product_content.product_color)
-
end
-
-
1
it 'filter by out of stocks' do
-
-
1
valid_keyword[:out_of_stocks] = true
-
-
1
post :list_trending_products, params: valid_keyword
-
-
1
expect(response_body['data'][0]['attributes']['stocks']).to eq(@catalogues.second.stocks)
-
end
-
-
1
it 'filters products by custom field values' do
-
1
custom_field_values = ['value1', 'value2']
-
1
catalogue_content1 = FactoryBot.create(:catalogue_content, catalogue: @catalogues.last, custom_field: @custom_field, value: custom_field_values.first)
-
1
catalogue_content2 = FactoryBot.create(:catalogue_content, catalogue: @catalogues.last, custom_field: @custom_field, value: custom_field_values.second)
-
-
1
post :list_trending_products, params: { slider: 1, custom_field_values: custom_field_values }
-
-
2
expect(JSON.parse(response.body)['data'].map { |item| item['id'] }).to include(@catalogues.last.id.to_s)
-
end
-
end
-
-
1
context 'with blank slider' do
-
-
1
it 'renders missing slider' do
-
1
post :list_trending_products, params: {}
-
1
expect(response_body['message']).to eq("missing slider in params")
-
end
-
end
-
-
1
context 'with invalid slider' do
-
-
1
it 'renders missing trending product' do
-
1
post :list_trending_products, params: {slider: 2}
-
1
expect(response_body['message']).to eq("No trending products found for the given slider")
-
end
-
end
-
end
-
-
1
private
-
-
1
def response_body
-
11
JSON.parse(response.body)
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockDashboard::WeeklyHomieeDealsController, type: :controller do
-
-
1
before do
-
3
@deal = FactoryBot.create(:deal)
-
3
@bg_image = fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))
-
weekly_deals_attributes = [
-
3
{ caption: "slider1", discount_percent: 1.0, url: "https://slider1", deal: @deal, bg_image: @bg_image },
-
{ caption: "slider2", discount_percent: 2.0, url: "https://slider2", deal: @deal, bg_image: @bg_image },
-
{ caption: "slider3", discount_percent: 3.0, url: "https://slider3", deal: @deal, bg_image: @bg_image }
-
]
-
-
3
@weekly_homiee_deal = create(:weekly_homiee_deal, status: true, weekly_deals_attributes: weekly_deals_attributes)
-
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a successful response with a list of deals' do
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockDashboard::WeeklyHomieeDeal.all.count)
-
end
-
end
-
-
1
describe 'GET #show' do
-
-
1
it 'returns a successful response with the details of a deal' do
-
1
get :show, params: { id: @weekly_homiee_deal.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response_2 = JSON.parse(response.body)
-
1
expect(parsed_response_2['data']['id']).to eq(@weekly_homiee_deal.id.to_s)
-
1
expect(parsed_response_2['data']['attributes']['weekly_deals'][0]).to have_key('bg_image')
-
end
-
-
end
-
-
1
describe 'GET #latest_weekly_deal' do
-
-
1
it 'latest_weekly_deal returns a successful response with the details of a deal' do
-
1
get :latest_weekly_deal, params: { id: @weekly_homiee_deal.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
parsed_response_3 = JSON.parse(response.body)
-
1
expect(parsed_response_3['data']['id']).to eq(@weekly_homiee_deal.id.to_s)
-
end
-
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockFavourites::FavouritesController, type: :controller do
-
1
before do
-
7
@account = FactoryBot.create(:account)
-
7
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@favourite = create(:favourite, user: @account)
-
7
@catalogue_0 = create(:catalogue)
-
7
@favourite_2 = create(:favourite, user: @account, favouriteable_id: @catalogue_0.id)
-
7
@account_2 = FactoryBot.create(:account)
-
7
@token_2 = BuilderJsonWebToken.encode(@account_2.id, token_type: 'login')
-
7
@catalogue = create(:catalogue)
-
7
@product_variant = create(:product_variant_group, catalogue: @catalogue)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a list of favourites for the user' do
-
-
1
get :index, params: { token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['attributes']['catalogue']['data']['id']).to eq(@favourite_2.favouriteable_id.to_s)
-
3
favorites = response_body['data'].map { |fav| fav['attributes']['catalogue']['data']['id'].to_i }
-
1
expect(favorites).to eq([ @favourite_2.favouriteable_id, @favourite.favouriteable_id])
-
-
end
-
-
1
it 'returns a list of favourites for the user sort by' do
-
-
1
get :index, params: { token: @token, sort_by: 'whats_new' }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'][0]['attributes']['catalogue']['data']['attributes']['created_at'].to_time.iso8601).to eq(@favourite_2.favouriteable.created_at.to_time.iso8601)
-
-
end
-
-
1
it 'returns an empty array if user has no favourites' do
-
1
get :index, params: { token: @token_2 }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response_body).to eq([])
-
-
end
-
end
-
-
1
describe 'POST #create' do
-
-
1
it 'creates a existing favourite for the user with valid parameters' do
-
1
post :create, params: { token: @token, favouriteable_id: @catalogue.id, product_variant_group_id: @product_variant.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['attributes']['selected_product_variant']['id']).to eq(@product_variant.id)
-
end
-
-
1
it 'returns errors if creation fails' do
-
1
post :create, params: { token: @token, favouriteable_id: @catalogue_0.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to eq("Product already exist in wishlist")
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys a favourite' do
-
1
delete :destroy, params: {token: @token, id: @favourite.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body).to include('message' => 'Destroy successfully')
-
end
-
-
1
it 'returns not found if the favourite does not exist' do
-
1
delete :destroy, params: {token: @token, id: 999 }
-
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
-
# Helper method to parse JSON response
-
1
def response_body
-
7
JSON.parse(response.body)
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe "BxBlockForgotPassword::PasswordsController", type: :request do
-
1
before(:all) do
-
1
PASSWORD = "Password@123"
-
1
@current_user = FactoryBot.create(:account, user_type: "seller")
-
1
@buyer_user = FactoryBot.create(:account, user_type: "buyer")
-
# @reset_token = []
-
1
@error_msg = "The email is not registered or Email id is not valid"
-
end
-
-
-
1
describe "forgot and reset password" do
-
1
context "forgot password" do
-
7
let(:forgot_password_url) { '/forgot_password' }
-
-
1
it "success" do
-
1
post forgot_password_url, params: { data: {"user_type": @current_user.user_type,"email": "#{@current_user.email}" } }
-
# @reset_token << JSON.parse(response.body)['message']['reset_token']
-
1
expect(response).to have_http_status(201)
-
end
-
-
1
it "seller forgot password success" do
-
1
post forgot_password_url, params: { data: {"user_type": 'seller',"email": "#{@current_user.email}" } }
-
1
expect(response).to have_http_status(201)
-
end
-
-
1
it "buyer forgot password success" do
-
1
post forgot_password_url, params: { data: {"user_type": 'buyer',"email": "#{@buyer_user.email}" } }
-
1
expect(response).to have_http_status(201)
-
end
-
-
1
it "email failures" do
-
1
post forgot_password_url, params: { data: {"user_type": @current_user.user_type, "email": "testmail.com" } }
-
1
expect(response).to have_http_status(422)
-
1
expect(JSON.parse(response.body)['errors'][0]['profile']).to eq(@error_msg)
-
end
-
-
1
it "user type failures" do
-
1
post forgot_password_url, params: { data: {"user_type": "buyer", "email": "#{@current_user.email}" } }
-
1
expect(response).to have_http_status(422)
-
1
expect(JSON.parse(response.body)['errors'][0]['profile']).to eq(@error_msg)
-
end
-
-
1
it "blank email failures" do
-
1
post forgot_password_url, params: { data: {"user_type": @current_user.user_type, "email": nil } }
-
1
expect(response).to have_http_status(422)
-
1
expect(JSON.parse(response.body)['errors'][0]['profile']).to eq('Email id should not be blank')
-
end
-
-
end
-
-
1
context "reset password" do
-
8
let(:reset_password_url) { '/reset_password' }
-
5
let(:token) { BuilderJsonWebToken.encode(@current_user.id, 10.minutes.from_now) }
-
1
it "password set successfully" do
-
1
patch reset_password_url, params: {
-
data: {
-
token: token,
-
new_password: PASSWORD,
-
confirm_password: PASSWORD
-
}
-
}
-
1
expect(response).to have_http_status 200
-
end
-
-
1
it 'returns the serialized account' do
-
1
patch reset_password_url, params: {
-
data: {
-
token: token,
-
new_password: PASSWORD,
-
confirm_password: PASSWORD
-
}
-
}
-
1
expect(JSON.parse(response.body)['data']).to be_present
-
end
-
-
1
it "reset password failures" do
-
1
patch reset_password_url, params: {
-
data: {
-
token: token,
-
new_password: PASSWORD,
-
confirm_password: "Test@1123"
-
}
-
}
-
1
expect(response).to have_http_status 422
-
end
-
-
1
it 'returns an error message' do
-
1
patch reset_password_url, params: {
-
data: {
-
token: 'invalid token',
-
new_password: PASSWORD,
-
confirm_password: PASSWORD
-
}
-
}
-
1
expect(JSON.parse(response.body)['errors'][0]['token']).to eq('Invalid token')
-
end
-
-
1
it 'returns an error message for blank params' do
-
1
patch reset_password_url, params: {
-
data: {
-
token: ' ',
-
new_password: PASSWORD,
-
confirm_password: PASSWORD
-
}
-
}
-
1
expect(JSON.parse(response.body)['errors'][0]['reset_password']).to eq('Token, New Password, and Confirm Password are required')
-
end
-
-
1
it 'returns an error expired message' do
-
1
expired_user = FactoryBot.create(:account)
-
1
expired_token = BuilderJsonWebToken.encode(expired_user.id,1.minutes.ago)
-
1
expired_user.update(reset_token: expired_token)
-
1
patch reset_password_url, params: {
-
data: {
-
token: expired_token,
-
new_password: PASSWORD,
-
confirm_password: PASSWORD
-
}
-
}
-
1
expect(JSON.parse(response.body)['errors'][0]['token']).to eq("Token has expired or has already been used")
-
end
-
-
1
it 'returns an error status' do
-
1
patch reset_password_url, params: {
-
data: {
-
token: token,
-
new_password: PASSWORD,
-
confirm_password: "invalid password"
-
}
-
}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
-
end
-
-
1
context "current password check" do
-
4
let(:current_password_url) { '/current_password' }
-
3
let(:valid_token) { BuilderJsonWebToken.encode(@current_user.id, 10.minutes.from_now) }
-
1
it "success" do
-
1
post current_password_url, params: {
-
data: {
-
token: valid_token,
-
current_password: PASSWORD
-
}
-
}
-
1
expect(response).to have_http_status(200)
-
end
-
-
1
it "fail wrong password" do
-
1
post current_password_url, params: {
-
data: {
-
token: valid_token,
-
current_password: "ssss"
-
}
-
}
-
1
expect(response).to have_http_status(422)
-
1
expect(JSON.parse(response.body)['data']).to eq(false)
-
1
expect(JSON.parse(response.body)['message']).to eq("Current Password is not correct")
-
end
-
-
-
# it "fail invalid token" do
-
# post current_password_url, params: {
-
# data: {
-
# token: "invalid_token",
-
# current_password: "ssss"
-
# }
-
# }
-
# expect(response).to have_http_status(422)
-
# end
-
-
1
it "fail token expire" do
-
1
expired_user = FactoryBot.create(:account)
-
1
expired_token = BuilderJsonWebToken.encode(expired_user.id,1.minutes.ago)
-
1
post current_password_url, params: {
-
data: {
-
token: expired_token,
-
current_password: "ssss"
-
}
-
}
-
1
expect(response).to have_http_status(422)
-
1
expect(JSON.parse(response.body)['data']).to eq(false)
-
end
-
-
-
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockInvoicebilling::InvoiceBillingsController, type: :controller do
-
-
1
before do
-
3
@customer = FactoryBot.create(:account, user_type: 'buyer')
-
3
@customer_2 = FactoryBot.create(:account, user_type: 'buyer')
-
3
@token_buyer = BuilderJsonWebToken.encode(@customer.id, token_type: 'login')
-
3
@token_buyer_2 = BuilderJsonWebToken.encode(@customer_2.id, token_type: 'login')
-
3
@seller = FactoryBot.create(:account, company_or_store_name: "byezzy", user_type: 'seller')
-
3
@catalogue = create(:catalogue, seller: @seller)
-
3
@product_content = create(:product_content, catalogue: @catalogue)
-
3
@order_status_delivered = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Delivered')
-
3
@order = create(:shopping_cart_order, customer: @customer)
-
3
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
3
@order.update(order_status: @order_status_delivered)
-
3
stub_request(:post, "https://secure.telr.com/gateway/order.json")
-
.to_return(body: { 'order' => { 'ref' => '123456789' } }.to_json, status: 200)
-
3
@order.update(transaction_id: "123456789")
-
3
@order_2 = create(:shopping_cart_order, customer: @customer_2)
-
3
@order_item_2 = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order_2)
-
end
-
-
1
describe 'GET #invoice_pdf' do
-
1
it 'returns a PDF file with the correct content' do
-
-
1
get :invoice_pdf, params: { order_id: @order.id, order_item_id: @order_item.id, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['data']['attributes']['order_id']).to eq(@order.id)
-
1
expect(JSON.parse(response.body)['data']['attributes']['invoice_pdf']).to match(/\/rails\/active_storage\/blobs\/.+\/invoice-.+\.pdf/)
-
end
-
-
1
it 'renders an error if the order is not found or not delivered' do
-
-
1
get :invoice_pdf, params: { order_id: @order_2.id, order_item_id: @order_item_2.id, token: @token_buyer_2 }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['error']).to eq("Order not found or not delivered")
-
end
-
-
1
it 'renders an error if the user is invalid' do
-
-
1
get :invoice_pdf, params: { order_id: @order.id, order_item_id: @order_item.id, token: @token_buyer_2 }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['error']).to eq("User Invalid")
-
end
-
end
-
end
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe 'BxBlockLogin::LoginsController', type: :request do
-
1
before(:all) do
-
1
LOGIN = "/bx_block_login/logins"
-
1
@current_user = create(:account, user_type: "buyer", activated: true)
-
1
image = fixture_file_upload('files/Sample.jpg', 'image/jpeg')
-
1
@current_user.profile_picture.attach(io: File.open(image), filename: 'Sample.jpg', content_type: 'image/jpeg')
-
1
@seller_pass = "Password@1234"
-
1
@current_user2 = create(:account, user_type: "seller", password: @seller_pass)
-
1
@token = BuilderJsonWebToken.encode(@current_user.id)
-
1
@doc_name = "document.pdf"
-
end
-
-
1
describe 'POST Login ' do
-
1
context "Login Successfully with Email" do
-
1
let(:params) do
-
{
-
5
"data": {
-
"type": "email_account",
-
"user_type": "seller",
-
"attributes": {
-
"email": @current_user2.email,
-
"password": "Password@1234"
-
}
-
}
-
}
-
end
-
1
it 'should return when account login with email Successfully' do
-
1
@current_user2.update(activated: true)
-
-
1
post LOGIN, params: params
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['meta']['document_status']).to eq("No documents uploaded")
-
end
-
-
1
it 'should return when account document in verification' do
-
1
@current_user3 = create(:account, user_type: "seller", password: @seller_pass, activated: true)
-
1
@seller_document1 = FactoryBot.create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", @doc_name))], account: @current_user3)
-
1
params[:data][:attributes][:email] = @current_user3.email
-
-
1
post LOGIN, params: params
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['meta']['document_status']).to eq("Your Document verification is in progress")
-
end
-
-
1
it 'should return when account document approved' do
-
1
@current_user4 = create(:account, user_type: "seller", password: @seller_pass, activated: true)
-
1
@seller_document1 = FactoryBot.create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", @doc_name))], account: @current_user4)
-
1
@seller_document1.update(approved: true)
-
1
params[:data][:attributes][:email] = @current_user4.email
-
-
1
post LOGIN, params: params
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['meta']['document_status']).to eq("Your document has been verified")
-
end
-
-
1
it 'should return when account document rejected' do
-
1
@current_user5 = create(:account, user_type: "seller", password: @seller_pass, activated: true)
-
1
@seller_document1 = FactoryBot.create(:seller_document,document_files: [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", @doc_name))], account: @current_user5)
-
1
@seller_document1.update(rejected: true)
-
1
params[:data][:attributes][:email] = @current_user5.email
-
-
1
post LOGIN, params: params
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['meta']['document_status']).to eq("Rejected: #{@seller_document1.document_name}")
-
end
-
-
1
it 'should return when account not found' do
-
1
post LOGIN, params: params
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors'][0]['failed_login']).to eq('The email is not register or not activated')
-
end
-
-
end
-
-
1
context "Login with Email for profile picture" do
-
1
let(:params) do
-
{
-
3
"data": {
-
"type": "email_account",
-
"user_type": "buyer",
-
"attributes": {
-
"email": "#{@current_user.email}",
-
"password": "Password@123"
-
}
-
}
-
}
-
end
-
-
1
it 'should return when account login with profile image Successfully' do
-
1
post LOGIN, params: params
-
1
expect(@current_user.reload.profile_picture).to be_attached
-
end
-
-
1
it 'should return when account login with error' do
-
1
params[:data][:attributes][:password] = @seller_pass
-
1
post LOGIN, params: params
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors'][0]['failed_login']).to eq('Email or Password incorrect please try again')
-
end
-
-
1
it 'should return when account login with error invalid type' do
-
1
params[:data][:type] = "invalid_type"
-
1
post LOGIN, params: params
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors'][0]['account']).to eq('Invalid Account Type')
-
end
-
-
end
-
-
1
context "sent otp" do
-
1
let(:params) do
-
{
-
1
"data": {
-
"attributes": {
-
"full_phone_number": @current_user.full_phone_number
-
}
-
}
-
}
-
end
-
1
it 'should send otp' do
-
1
allow_any_instance_of(AccountBlock::SmsOtp).to receive(:generate_pin_and_valid_date) do |sms_otp|
-
1
sms_otp.pin = '54321'
-
1
sms_otp.valid_until = Time.current + 5.minutes
-
end
-
1
stub_request(:post, "https://el.cloud.unifonic.com/rest/SMS/messages")
-
.with(
-
body: {
-
"AppSid" => ENV['UNIFONIC_APPSID'],
-
"Body" => "Your Pin Number is 54321",
-
"Recipient" => "+#{@current_user.full_phone_number}",
-
"SenderID" => ENV['UNIFONIC_SENDERID'],
-
"async" => "true"
-
},
-
headers: {
-
'Accept' => '*/*',
-
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
-
'Content-Type' => 'application/x-www-form-urlencoded',
-
'User-Agent' => 'Ruby'
-
}
-
)
-
.to_return(status: 200, body: "", headers: {})
-
1
post '/send_login_otp',params: params, headers: {token: @token}
-
1
expect(response).to have_http_status(:created)
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockOrderManagement::AnchantoWmsController, type: :controller do
-
20
let(:seller) { create(:account, user_type: 'seller') }
-
5
let(:buyer) { create(:account, user_type: 'buyer') }
-
3
let(:buytoken) { BuilderJsonWebToken.encode(buyer.id) }
-
16
let(:catalogue) { create(:catalogue, seller: seller, fulfilled_type: 'byezzy') }
-
3
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Ordered') }
-
2
let(:order) { create(:shopping_cart_order, customer: buyer, order_status: order_status) }
-
1
let(:product_content) { create(:product_content, catalogue: catalogue) }
-
2
let(:order_item) { create(:shopping_cart_order_item, catalogue: catalogue, order: order) }
-
1
let(:product_content) { create(:product_content, catalogue: catalogue) }
-
15
let(:token) { BuilderJsonWebToken.encode(seller.id) }
-
10
let(:valid_auth_token) { 'valid_auth_token' }
-
9
let(:valid_warehouse_code) { 'WH123' }
-
1
let(:wms_product_info) { create(:wms_product_info, seller: seller, catalogue: catalogue) }
-
6
let(:consignment_api) { 'https://uatapi.anchanto.com/rest/v1/consignments' }
-
2
let(:order1) { create(:shopping_cart_order, customer: buyer, order_status: order_status) }
-
3
let(:not_found_msg) { 'Order not found' }
-
-
1
describe 'POST #create_wms_product' do
-
1
context 'with valid params and successful response from WMS API' do
-
1
let(:valid_wms_response) do
-
{
-
1
'response' => 'success',
-
'message' => 'Product created',
-
'data' => [
-
{ 'product_information_id' => [6] },
-
{ 'product_dimensions_info' => { 'sku-test-wms' => 6 } }
-
]
-
}.to_json
-
end
-
-
1
before do
-
1
stub_request(:post, 'https://uatapi.anchanto.com/rest/v1/products')
-
.to_return(status: 200, body: valid_wms_response)
-
end
-
-
1
it 'creates a WmsProductInfo and returns success response' do
-
1
expect do
-
1
post :create_wms_product,
-
params: { authorization: valid_auth_token, warehouse_code: valid_warehouse_code, catalogue_id: catalogue.id,
-
token: token }
-
end.to change(BxBlockOrderManagement::WmsProductInfo, :count).by(1)
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['response']).to eq('success')
-
1
expect(parsed_response['message']).to eq('Product created')
-
end
-
end
-
-
1
context 'with invalid params' do
-
1
it 'returns an unprocessable entity status' do
-
1
post :create_wms_product, params: { token: token, catalogue_id: nil }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq('Catalogue not found')
-
end
-
-
1
it 'returns an unprocessable entity status for invalid seller' do
-
1
post :create_wms_product, params: { token: buytoken, catalogue_id: nil }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq('Invalid seller')
-
end
-
end
-
-
1
context 'with an invalid response from the WMS API' do
-
1
let(:invalid_wms_response) do
-
{
-
1
'response' => 'failure',
-
'message' => 'Product could not be created',
-
'data' => ['Base uom dimension is required']
-
}.to_json
-
end
-
-
1
before do
-
1
stub_request(:post, 'https://uatapi.anchanto.com/rest/v1/products')
-
.to_return(status: 400, body: invalid_wms_response)
-
end
-
-
1
it 'does not create WmsProductInfo and returns error response' do
-
1
expect do
-
1
post :create_wms_product,
-
params: { token: token, authorization: valid_auth_token, warehouse_code: valid_warehouse_code,
-
catalogue_id: catalogue.id }
-
end.not_to change(BxBlockOrderManagement::WmsProductInfo, :count)
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['response']).to eq('failure')
-
1
expect(parsed_response['message']).to eq('Product could not be created')
-
end
-
end
-
end
-
-
1
describe 'POST #create_consignment_order' do
-
1
let(:valid_consignment_order_response) do
-
{
-
1
"response": 'success',
-
"message": 'Consignment created',
-
"order_number": 'POBTUSER123520835451308',
-
"data": []
-
}.to_json
-
end
-
-
1
before do
-
1
stub_request(:post, consignment_api)
-
.to_return(status: 200, body: valid_consignment_order_response)
-
end
-
-
1
it 'creates a consignment order and returns success response' do
-
1
expect do
-
1
post :create_consignment_order,
-
params: { authorization: valid_auth_token, quantity: 1, warehouse_code: valid_warehouse_code,
-
catalogue_id: catalogue.id, token: token }
-
end.to change(BxBlockOrderManagement::WmsConsignmentOrder, :count).by(1)
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['response']).to eq('success')
-
1
expect(parsed_response['message']).to eq('Consignment created')
-
1
expect(parsed_response['order_number']).to eq('POBTUSER123520835451308')
-
end
-
end
-
-
1
describe 'POST #create_consignment_order with invalid params' do
-
1
before do
-
3
stub_request(:post, consignment_api)
-
.to_return(status: 401, body: { message: 'Missing required params' }.to_json)
-
end
-
-
1
it 'returns an unprocessable entity status consign order' do
-
1
post :create_consignment_order,
-
params: { token: token, authorization: '', warehouse_code: '', quantity: 1, catalogue_id: catalogue.id }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq('Missing required params')
-
end
-
-
1
it 'returns an unprocessable entity quantity error' do
-
1
post :create_consignment_order,
-
params: { token: token, authorization: 'adf', warehouse_code: 'asd', quantity: '',
-
catalogue_id: catalogue.id }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq('Missing quantity')
-
end
-
-
1
it 'returns an unprocessable entity status for invalid seller consign order' do
-
1
post :create_consignment_order,
-
params: { token: buytoken, authorization: '', warehouse_code: '', catalogue_id: catalogue.id }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq('Invalid seller')
-
end
-
end
-
-
1
describe 'POST #create_consignment_order with invalid response from WMS API' do
-
1
let(:invalid_consignment_order_response) do
-
{
-
1
"errors": 'Warehouse mismatch!'
-
}.to_json
-
end
-
-
1
before do
-
1
stub_request(:post, consignment_api)
-
.to_return(status: 401, body: invalid_consignment_order_response)
-
end
-
-
1
it 'returns an error response and does not create a consignment order' do
-
1
post :create_consignment_order,
-
params: { token: token, authorization: valid_auth_token, warehouse_code: '', quantity: 1,
-
catalogue_id: catalogue.id }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors']).to eq('Warehouse mismatch!')
-
end
-
end
-
-
1
describe 'POST #create_b2c_order' do
-
1
context 'with valid params and successful response from WMS Order API' do
-
1
let(:valid_wms_api_order_response) do
-
{
-
1
"response": 'success',
-
"message": 'Order created',
-
"order_number": order.order_number,
-
"data": [],
-
"state": 'draft'
-
}.to_json
-
end
-
-
1
before do
-
1
order.order_items << order_item
-
1
stub_request(:post, 'https://uatapi.anchanto.com/rest/v1/b2c/orders')
-
.to_return(status: 200, body: valid_wms_api_order_response)
-
end
-
-
1
it 'creates a WmsB2cOrder and returns success response' do
-
1
post :create_b2c_order,
-
params: { authorization: valid_auth_token, warehouse_code: valid_warehouse_code, order_id: order.id,
-
token: token }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['response']).to eq('success')
-
1
expect(parsed_response['message']).to eq('Order created')
-
end
-
end
-
-
1
context 'with invalid params Wms Order API' do
-
1
it 'returns an unprocessable entity status' do
-
1
post :create_b2c_order, params: { token: token, order_id: nil }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq(not_found_msg)
-
end
-
end
-
-
1
context 'with invalid Wms Order API' do
-
1
it 'returns an not found status' do
-
1
post :create_b2c_order, params: { token: token, order_id: order1.id }
-
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq('No byezzy products ordered')
-
end
-
end
-
end
-
-
1
describe 'GET #b2c_order_index' do
-
1
let(:external_response) do
-
{
-
2
"data": [
-
{
-
"attributes": {
-
"number": '1',
-
"state": 'draft',
-
"order_items": [
-
{ "sku": catalogue.bibc, "paid_price": '3500.0', "quantity": 1 }
-
]
-
}
-
}
-
],
-
"meta": { "current_page": 1, "total_pages": 1, "total_count": 1 }
-
}.to_json
-
end
-
-
1
before do
-
2
stub_request(:get, 'https://uatapi.anchanto.com/rest/v1/b2c/orders?filter[created_at]=&page[number]=1&page[size]=10')
-
.to_return(status: 200, body: external_response)
-
end
-
-
1
context 'when the request is successful' do
-
1
it 'returns filtered orders for the seller' do
-
1
post :b2c_order_index,
-
params: { per_page: 10, page: 1, authorization: valid_auth_token, warehouse_code: valid_warehouse_code,
-
token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['orders'].size).to eq(1)
-
1
expect(response_body['orders'][0]['order_items'].size).to eq(1)
-
1
expect(response_body['orders'][0]['order_items'][0]['sku']).to eq(catalogue.bibc)
-
end
-
end
-
-
1
context 'when the request fails' do
-
1
before do
-
1
stub_request(:get, 'https://uatapi.anchanto.com/rest/v1/b2c/orders?filter[created_at]=&page[number]=1&page[size]=10')
-
.to_return(status: 500, body: { message: 'Internal Server Error' }.to_json)
-
end
-
-
1
it 'returns an error response' do
-
1
post :b2c_order_index,
-
params: { per_page: 10, page: 1, authorization: valid_auth_token, warehouse_code: valid_warehouse_code,
-
token: token }
-
-
1
expect(response).to have_http_status(:internal_server_error)
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['message']).to eq('Internal Server Error')
-
end
-
end
-
end
-
-
1
describe 'GET #b2c_order_show' do
-
1
let(:external_response) do
-
{
-
1
"data": {
-
"attributes": {
-
"number": 1,
-
"state": 'draft',
-
"order_items": [
-
{ "sku": catalogue.bibc, "paid_price": '3500.0', "quantity": 1 }
-
]
-
}
-
},
-
"meta": {}
-
}.to_json
-
end
-
-
1
context 'when the request is successful' do
-
1
before do
-
1
stub_request(:get, 'https://uatapi.anchanto.com/rest/v1/b2c/orders/1/details')
-
.to_return(status: 200, body: external_response)
-
end
-
1
it 'returns the order details filtered by seller' do
-
1
post :b2c_order_show,
-
params: { order_number: 1, authorization: valid_auth_token, warehouse_code: valid_warehouse_code,
-
token: token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['orders'].size).to eq(0)
-
# expect(response_body["orders"][0]["order_items"].size).to eq(1)
-
# expect(response_body["orders"][0]["order_items"][0]["sku"]).to eq(catalogue.bibc)
-
end
-
end
-
-
1
context 'when the request fails' do
-
1
before do
-
1
stub_request(:get, 'https://uatapi.anchanto.com/rest/v1/b2c/orders/1/details')
-
.to_return(status: 404, body: { message: not_found_msg }.to_json)
-
end
-
-
1
it 'returns an error response' do
-
1
post :b2c_order_show,
-
params: { order_number: 1, authorization: valid_auth_token, warehouse_code: valid_warehouse_code,
-
token: token }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['message']).to eq(not_found_msg)
-
end
-
end
-
end
-
-
1
let(:event_params) do
-
{
-
4
event_parameters: {
-
warehouse_code: 'WH123',
-
seller_email: seller.email,
-
api_key: 'some_api_key'
-
},
-
event: {
-
order_number: 'ORD123',
-
old_state: 'pending',
-
new_state: 'shipped',
-
event_on: '2024-11-05 12:40:12 +0000',
-
time_zone: 'UTC'
-
},
-
products: [
-
{ sku: catalogue.bibc, quantity: 10, batch: 'BATCH001', expiry_date: '2025-12-31', usable_quantity: 8 }
-
]
-
}
-
end
-
-
1
describe 'POST #event_grn_status_update_in_wms' do
-
1
it 'processes the WMS event and creates records' do
-
1
expect do
-
1
post :event_grn_status_update_in_wms, params: event_params
-
end.to change(BxBlockOrderManagement::WmsEventUpdate, :count).by(1)
-
-
1
created_event = BxBlockOrderManagement::WmsEventUpdate.last
-
1
expect(created_event.warehouse_code).to eq('WH123')
-
1
expect(created_event.seller_email).to eq(seller.email)
-
1
expect(created_event.products).to be_present
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'notifies the seller with the correct details' do
-
1
post :event_grn_status_update_in_wms, params: event_params
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
end
-
-
1
describe 'POST #event_consignment_status_update_in_wms' do
-
1
it 'processes the consignment event and creates records' do
-
1
expect do
-
1
post :event_consignment_status_update_in_wms, params: event_params
-
end.to change(BxBlockOrderManagement::WmsEventUpdate, :count).by(1)
-
-
1
created_event = BxBlockOrderManagement::WmsEventUpdate.last
-
1
expect(created_event.seller_email).to eq(seller.email)
-
end
-
end
-
-
1
describe 'POST #event_b2c_shipment_status_update_in_wms' do
-
1
it 'processes the B2C shipment event and creates records' do
-
1
expect do
-
1
post :event_b2c_shipment_status_update_in_wms, params: event_params
-
end.to change(BxBlockOrderManagement::WmsEventUpdate, :count).by(1)
-
-
1
created_event = BxBlockOrderManagement::WmsEventUpdate.last
-
1
expect(created_event.time_zone).to eq('UTC')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockOrderManagement::DeliveryRequestsController, type: :controller do
-
8
let(:account) { create(:account, user_type: 'seller') }
-
8
let(:customer) { create(:account, user_type: 'buyer') }
-
7
let(:warehouse) { create(:warehouse, account: account) }
-
8
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Processing')}
-
8
let(:order) {create(:shopping_cart_order, customer: customer)}
-
5
let(:delivery_request) { create(:delivery_request, warehouse: warehouse, seller: account, order: order) }
-
-
1
let(:valid_attributes) do
-
{
-
2
data: {
-
attributes: {
-
warehouse_id: warehouse.id,
-
warehouse_name: warehouse.warehouse_name,
-
order_number: order.order_number,
-
address_1: '123 Main St',
-
address_2: 'Apt 456',
-
}
-
}
-
}
-
end
-
-
1
before(:each) do
-
7
@token = BuilderJsonWebToken.encode(account.id)
-
7
order.update(order_status: order_status)
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success response index' do
-
1
get :index, params: { token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success response show' do
-
1
get :show, params: { token: @token, id: delivery_request.id }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'with valid params' do
-
-
1
it 'renders a JSON response with the new delivery request' do
-
1
post :create, params: { token: @token }.merge(valid_attributes)
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(response_body['data']['attributes']['warehouse_name']).to eq(warehouse.warehouse_name)
-
end
-
end
-
-
-
1
context 'with invalid params' do
-
1
it 'renders a JSON response with errors for the new delivery request' do
-
1
valid_attributes[:data][:attributes][:order_number] = "1234"
-
1
post :create, params: valid_attributes.merge({ token: @token })
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body['errors']).to include("Order number is invalid")
-
end
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
context 'with valid/invalid params' do
-
1
let(:new_attributes) do
-
{
-
2
data: {
-
attributes: {
-
address_1: 'test add update'
-
}
-
}
-
}
-
end
-
-
1
it 'updates the requested delivery request' do
-
1
put :update, params: { token: @token, id: delivery_request.id }.merge(new_attributes)
-
1
delivery_request.reload
-
1
expect(response_body['data']['attributes']['address_1']).to eq(delivery_request.address_1)
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'renders a JSON response with errors for the delivery request' do
-
1
new_attributes[:data][:attributes][:address_1] = ""
-
1
put :update, params: {token: @token, id: delivery_request.id }.merge(new_attributes)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body['errors']).to include("Address 1 is missing or select geo location")
-
end
-
-
end
-
-
# context 'with invalid params' do
-
# it 'renders a JSON response with errors for the delivery request' do
-
# new_attributes['data']['attributes']['address_1'] = ""
-
# put :update, params: {token: @token, id: delivery_request.id }.merge(new_attributes)
-
# expect(response).to have_http_status(:unprocessable_entity)
-
# expect(response_body['errors']).to include("Address 1 is missing or select geo location")
-
# end
-
# end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the requested delivery requested' do
-
1
delete :destroy, params: { token: @token, id: delivery_request.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to include("Delivery request deleted succesfully!")
-
end
-
end
-
-
1
private
-
-
1
def response_body
-
5
JSON.parse(response.body)
-
end
-
end
-
1
require 'rails_helper'
-
1
RSpec.describe BxBlockOrderManagement::OrderStatuesController, type: :controller do
-
-
2
let (:order_status) {create(:order_status)}
-
3
let(:account) { FactoryBot.create(:account) }
-
1
before(:each) do
-
2
@token = BuilderJsonWebToken.encode(account.id)
-
end
-
-
1
describe 'GET#OrderStatus Listing' do
-
1
context 'list of order_statuses' do
-
1
it 'should return order_statuses' do
-
1
get :index, params: { token: @token }
-
1
expect(response).to have_http_status :ok
-
end
-
end
-
end
-
-
1
describe 'GET# Show Order status' do
-
1
context 'Show order_status' do
-
1
it 'should show order_status' do
-
1
get :show, params: { token: @token, id: order_status.id }
-
1
expect(response).to have_http_status :ok
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockOrderManagement::StockIntakesController, type: :controller do
-
10
let(:seller) { create(:account, user_type: 'seller') }
-
8
let(:catalogue) { create(:catalogue, seller: seller) }
-
5
let(:stock_intake) { create(:stock_intake, seller: seller, catalogue: catalogue) }
-
-
1
before(:each) do
-
9
@token = BuilderJsonWebToken.encode(seller.id)
-
end
-
-
1
let(:valid_attributes) do
-
{
-
2
token: @token,
-
stock_intake: {
-
catalogue_id: catalogue.id,
-
stock_value: 2000,
-
stock_qty: 23,
-
ship_date: Date.tomorrow,
-
receiving_date: Date.tomorrow + 2.days
-
}
-
}
-
end
-
-
1
let(:invalid_attributes) do
-
{
-
2
token: @token,
-
stock_intake: {
-
catalogue_id: nil,
-
stock_value: -100,
-
stock_qty: 0,
-
ship_date: Date.yesterday,
-
receiving_date: Date.yesterday + 2.days
-
}
-
}
-
end
-
-
1
describe 'GET #index' do
-
1
it 'index returns a success response' do
-
1
get :index, params: {token: @token}
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'show returns a success response' do
-
1
get :show, params: {token: @token, id: stock_intake.id }
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'create with valid params' do
-
1
it 'creates a new StockIntake' do
-
1
expect {
-
1
post :create, params: valid_attributes
-
}.to change(BxBlockOrderManagement::StockIntake, :count).by(1)
-
end
-
-
1
it 'create renders a JSON response with the new stock_intake' do
-
1
post :create, params: valid_attributes
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'create with invalid params' do
-
1
it 'create renders a JSON response with errors for the new stock_intake' do
-
1
post :create, params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to match(/errors/)
-
end
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
context 'update with valid params' do
-
1
let(:new_attributes) do
-
{
-
2
token: @token,
-
stock_intake: {
-
stock_value: 3000
-
}
-
}
-
end
-
-
1
it 'updates the requested stock_intake' do
-
1
put :update, params: { id: stock_intake.id }.merge(new_attributes)
-
1
stock_intake.reload
-
1
expect(stock_intake.stock_value).to eq(stock_intake.stock_value)
-
end
-
-
1
it 'update renders a JSON response with the stock_intake' do
-
1
put :update, params: { id: stock_intake.id }.merge(new_attributes)
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context 'update with invalid params' do
-
1
it 'update renders a JSON response with errors for the stock_intake' do
-
1
put :update, params: { id: stock_intake.id }.merge(invalid_attributes)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to match(/errors/)
-
end
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the requested stock_intake' do
-
1
stock_intake_des = create(:stock_intake, seller: seller, catalogue: catalogue)
-
1
expect {
-
1
delete :destroy, params: {token: @token, id: stock_intake_des.id }
-
}.to change(BxBlockOrderManagement::StockIntake, :count).by(-1)
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to eq("Stock intake deleted succesfully!")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSalesreporting::ProductViewsController, type: :controller do
-
-
5
let(:catalogue) { create(:catalogue, status: true) }
-
5
let(:user) {create(:account, user_type: "buyer")}
-
3
let(:token) { BuilderJsonWebToken.encode(user.id) }
-
2
let(:invalid_user) { create(:account, user_type: "seller") }
-
2
let(:token2) { BuilderJsonWebToken.encode(invalid_user.id) }
-
-
-
1
let(:valid_attributes) do
-
{
-
2
product_view: {
-
catalogue_id: catalogue.id,
-
user_id: user.id
-
}
-
}
-
end
-
-
1
describe 'POST #create' do
-
1
context 'with valid params' do
-
-
1
it 'renders a JSON response with the new product view' do
-
1
post :create, params: valid_attributes
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(response_body['success']).to eq(true)
-
end
-
end
-
-
-
1
context 'with invalid params' do
-
1
it 'renders a JSON response with errors for the new product view' do
-
1
valid_attributes[:product_view][:catalogue_id] = ""
-
1
post :create, params: valid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body['errors']).to include("Catalogue must exist")
-
end
-
end
-
end
-
-
1
describe 'GET #browsing_history' do
-
1
context 'when user is valid/invalid' do
-
-
1
it 'returns a success response' do
-
1
product_view = create(:product_view, user: user, catalogue: catalogue, viewed_at: 10.days.ago)
-
1
get :browsing_history, params: {token: token}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data'].first['attributes']['viewed_at'].to_json).to eq(product_view.viewed_at.to_json)
-
end
-
-
1
it 'returns a success response with latest view' do
-
1
product_view1 = create(:product_view, user: user, catalogue: catalogue, viewed_at: Time.now)
-
1
get :browsing_history, params: {token: token}
-
-
1
expect(response_body['data'].first['attributes']['viewed_at'].to_json).to eq(product_view1.viewed_at.to_json)
-
end
-
-
1
it 'returns a error response' do
-
1
get :browsing_history, params: {token: token2}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['errors']).to eq('Buyer is invalid')
-
end
-
-
-
end
-
end
-
-
1
private
-
-
1
def response_body
-
5
JSON.parse(response.body)
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSalesreporting::ReportsController, type: :controller do
-
-
-
1
before(:all) do
-
1
@seller = create(:account, user_type: "seller")
-
1
@token = BuilderJsonWebToken.encode(@seller.id)
-
1
@catalogue = create(:catalogue, seller: @seller)
-
1
@customer = create(:account, user_type: "buyer")
-
1
@order_status_on_going = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'On Going')
-
1
@order_status_ordered = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Ordered')
-
1
@order_status_delivered = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Delivered')
-
1
@order = create(:shopping_cart_order, customer: @customer, order_status: @order_status_on_going)
-
1
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
1
@order.order_items << @order_item
-
1
@order.update!(order_status: @order_status_ordered)
-
1
@order.update!(order_status: @order_status_delivered)
-
1
@product_view = create(:product_view, catalogue: @catalogue, user: @customer)
-
1
@ordered_product_sales = @order.final_price
-
1
@units_ordered = @order.total_items || 0
-
1
@units_ordered_by_items = @order_item.quantity
-
1
@total_order_item = @order.order_items.count
-
1
@average_sales_per_order_item = @ordered_product_sales / @total_order_item
-
1
@average_units_per_order_item = @units_ordered / @total_order_item
-
1
@average_selling_price = @ordered_product_sales / @total_order_item
-
1
@page_views_total = BxBlockSalesreporting::ProductView.where(catalogue_id: @catalogue.id).count
-
1
@page_views_percentage = 100
-
1
@order_date = Date.today.strftime('%Y-%m-%d')
-
-
1
@catalogue2 = create(:catalogue, besku: @catalogue.besku, seller: @seller)
-
1
@order2 = create(:shopping_cart_order, customer: @customer, order_status: @order_status_ordered)
-
1
@order_item2 = create(:shopping_cart_order_item, catalogue: @catalogue2, order: @order2, quantity: 1, price: 100.0)
-
1
@order2.order_items << @order_item2
-
end
-
-
-
1
let(:valid_attributes) do
-
{
-
10
token: @token,
-
start_date: Date.today,
-
end_date: Date.tomorrow,
-
report_type: "sales_report" # sales_report sales_and_traffic_report return_report compare_sales
-
}
-
end
-
-
1
describe 'POST #sales_performance' do
-
1
context 'with valid params' do
-
1
it 'renders a JSON response with the sales performance sales report' do
-
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response_body['results']).not_to be_empty
-
1
expect(response_body['results'][0]['date']).to eq(@order_date)
-
1
expect(response_body['results'][0]['ordered_product_sales']).to eq(@ordered_product_sales)
-
1
expect(response_body['results'][0]['units_ordered']).to eq(@units_ordered)
-
1
expect(response_body['results'][0]['total_order_item']).to eq(@total_order_item)
-
1
expect(response_body['results'][0]['average_sales_per_order_item']).to eq(@average_sales_per_order_item)
-
1
expect(response_body['results'][0]['average_units_per_order_item']).to eq(@average_units_per_order_item)
-
1
expect(response_body['results'][0]['average_selling_price']).to eq(@average_selling_price)
-
1
expect(response_body['results'][0]['order_item_sessions_total']).to eq(1)
-
1
expect(response_body['results'][0]['order_item_session_percentage']).to eq(100.0)
-
end
-
-
1
it 'renders a JSON response with the sales and traffic report' do
-
1
valid_attributes[:report_type] = "sales_and_traffic_report"
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response).to have_http_status(:ok)
-
-
1
expect(response_body['results']).not_to be_empty
-
1
expect(response_body['results'][0]['parent_besku']).to eq(@catalogue.besku)
-
1
expect(response_body['results'][0]['child_besku']).to eq("N/A")
-
1
expect(response_body['results'][0]['title']).to eq(@catalogue.product_title)
-
1
expect(response_body['results'][0]['sku']).to eq(@catalogue.sku)
-
1
expect(response_body['results'][0]['sessions_total']).to eq(1)
-
1
expect(response_body['results'][0]['sessions_percentage']).to eq(100.0)
-
1
expect(response_body['results'][0]['page_views_total']).to eq(@page_views_total)
-
1
expect(response_body['results'][0]['page_views_percentage_total']).to eq(@page_views_percentage)
-
1
expect(response_body['results'][0]['featured_offer_buy_box_per']).to eq(100.0)
-
1
expect(response_body['results'][0]['units_ordered']).to eq(@units_ordered_by_items)
-
1
expect(response_body['results'][0]['ordered_product_sales']).to eq(@order_item.price)
-
1
expect(response_body['results'][0]['total_order_item']).to eq(@total_order_item)
-
end
-
-
1
it 'renders a JSON response with the return report' do
-
1
valid_attributes[:report_type] = "return_report"
-
1
post :sales_performance, params: valid_attributes
-
-
-
1
expect(response_body['results']).not_to be_empty
-
1
expect(response_body['results'][0]['date']).to eq(@order_date)
-
1
expect(response_body['results'][0]['ordered_product_sales']).to eq(@ordered_product_sales)
-
1
expect(response_body['results'][0]['units_ordered']).to eq(@units_ordered)
-
1
expect(response_body['results'][0]['total_order_item']).to eq(@total_order_item)
-
1
expect(response_body['results'][0]['units_refunded']).to eq(0)
-
1
expect(response_body['results'][0]['refund_rate']).to eq(0)
-
1
expect(response_body['results'][0]['feedback_received']).to eq(0)
-
1
expect(response_body['results'][0]['negative_feedback_received']).to eq(0)
-
1
expect(response_body['results'][0]['received_negative_feedback_rate']).to eq(0)
-
1
expect(response_body['results'][0]['a_z_claims_granted']).to eq(0)
-
1
expect(response_body['results'][0]['claims_amount']).to eq(0)
-
end
-
-
1
it 'renders a JSON response with the return report sorted by date in descending order' do
-
-
1
post :sales_performance, params: valid_attributes.merge({ sort_by: 'date', sort_order: 'desc' })
-
-
1
expect(response_body['results']).not_to be_empty
-
1
expect(response_body['results'][0]['date']).to eq(@order_date)
-
end
-
-
1
it 'renders a JSON response with the compare_sales report' do
-
1
valid_attributes[:report_type] = "compare_sales"
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response_body['results']).not_to be_empty
-
1
expect(response_body['results']['today_so_far']).to have_key('total_order_item')
-
1
expect(response_body['results']['yesterday']).to have_key('units_ordered')
-
1
expect(response_body['results']['same_day_last_week']).to have_key('ordered_product_sales')
-
1
expect(response_body['results']['same_day_last_year']).to have_key('average_units_or_order_item')
-
1
expect(response_body['results']['percentage_change_from_yesterday']).to have_key('average_sales_or_order_item')
-
1
expect(response_body['results']['percentage_change_from_same_day_last_week']).to have_key('average_sales_or_order_item')
-
end
-
end
-
-
1
context 'with missing params' do
-
1
it 'renders a JSON error response when return type params are missing' do
-
1
post :sales_performance, params: { token: @token }
-
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['errors']).to eq("Report type is required")
-
end
-
-
1
it 'renders a JSON error response when start_date and end_date params are missing' do
-
1
post :sales_performance, params: { token: @token, report_type: "report_type" }
-
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['errors']).to eq("Please provide start_date and end_date")
-
end
-
-
1
it 'renders a JSON error response when return type params are missing' do
-
1
post :sales_performance, params: { token: @token, report_type: "report_type", start_date: Date.today, end_date: Date.today }
-
-
1
response_body = JSON.parse(response.body)
-
-
1
expect(response_body['results']['error']).to eq('Invalid report type')
-
end
-
end
-
end
-
-
1
describe 'POST #sales_performance #export_sales_report' do
-
1
before do
-
5
valid_attributes[:export_csv] = "true"
-
5
@date = "Date"
-
5
@ordered_product_sales = "Ordered Product Sales"
-
5
@units_ordered = "Units Ordered"
-
5
@total_order_item = "Total Order Item"
-
end
-
1
context '#export_sales_report with valid params' do
-
1
it 'renders a csv response with the sales performance sales report' do
-
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response_body['headers']).to eq([@date, @ordered_product_sales, @units_ordered, @total_order_item, "Average Sales Per Order Item", "Average Units Per Order Item", "Average Selling Price", "Order Item Sessions Total", "Order Item Session Percentage"])
-
end
-
-
1
it 'renders a csv response with the sales and traffic report' do
-
1
valid_attributes[:report_type] = "sales_and_traffic_report"
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response_body['headers']).to eq(["Parent Besku", "Child Besku", "Title", "Sku", "Sessions Total", "Sessions Percentage", "Page Views Total", "Page Views Percentage Total", "Featured Offer Buy Box Per", @units_ordered, "Units Ordered Percentage", @ordered_product_sales, @total_order_item])
-
end
-
-
1
it 'renders a csv response with the return report' do
-
1
valid_attributes[:report_type] = "return_report"
-
1
post :sales_performance, params: valid_attributes
-
-
-
1
expect(response_body['headers']).to eq([@date, @ordered_product_sales, @units_ordered, @total_order_item, "Units Refunded", "Refund Rate", "Feedback Received", "Negative Feedback Received", "Received Negative Feedback Rate", "A Z Claims Granted", "Claims Amount"])
-
end
-
-
1
it 'renders a csv response with the compare_sales report' do
-
1
valid_attributes[:report_type] = "compare_sales"
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response_body['headers']).to eq(["Period", @total_order_item, @units_ordered, @ordered_product_sales, "Average Units Or Order Item", "Average Sales Or Order Item"])
-
1
expect(response_body['values']['Period']).to eq(["Today So Far", "Yesterday", "Same Day Last Week", "Same Day Last Year", "Percentage Change From Yesterday", "Percentage Change From Same Day Last Week", "Percentage Change From Same Day Last Year"])
-
1
expect(response_body['values'][@total_order_item]).to all(be_a(Integer))
-
end
-
-
1
it 'renders a error response with the sales performance sales report' do
-
1
valid_attributes[:start_date] = Date.today - 3.days
-
1
valid_attributes[:end_date] = Date.today - 2.days
-
-
1
post :sales_performance, params: valid_attributes
-
-
1
expect(response_body['errors']).to eq("No report data available for export")
-
end
-
end
-
-
end
-
-
1
private
-
-
1
def csv_response
-
CSV.parse(response.body, headers: true)
-
end
-
-
1
def response_body
-
51
JSON.parse(response.body)
-
end
-
end
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe "BxBlockSeoSetting::SeoSettingsController", type: :request do
-
1
before(:all) do
-
1
BxBlockSeoSetting::SeoSetting.all.delete_all
-
1
@seo_setting = FactoryBot.create(:seo_setting)
-
end
-
-
1
let(:valid_attributes) {
-
{
-
2
"data": {
-
"attributes": {
-
"page_name": "Page#{rand(1000..9999)}",
-
"meta_title": "Nam lobortis sapien at dui porta dictum",
-
"meta_description": "Suspendisse finibus finibus tortor, vel tincidunt ex gravida mollis."
-
}
-
}
-
}
-
}
-
-
1
let(:invalid_attributes) {
-
{
-
3
"data": {
-
"attributes": {
-
"page_name": nil,
-
"meta_title": "eget pulvinar massa sagittis",
-
"meta_description": "Proin sed felis sit amet ante blandit scelerisque ac placerat purus."
-
}
-
}
-
}
-
}
-
-
1
describe "GET /index" do
-
1
it "renders a successful response" do
-
1
get bx_block_seo_setting_seo_settings_url
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe "GET /show" do
-
1
it "renders a successful response" do
-
1
get bx_block_seo_setting_seo_setting_url(@seo_setting)
-
1
expect(response).to be_successful
-
end
-
end
-
-
1
describe "POST /create" do
-
1
context "with valid parameters" do
-
1
it "creates a new SeoSetting" do
-
1
expect {
-
1
post bx_block_seo_setting_seo_settings_url,
-
params: valid_attributes
-
}.to change(BxBlockSeoSetting::SeoSetting, :count).by(1)
-
end
-
-
1
it "renders a JSON response with the new seo_setting" do
-
1
post bx_block_seo_setting_seo_settings_url,
-
params:valid_attributes
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context "with invalid parameters" do
-
1
it "does not create a new SeoSetting" do
-
1
expect {
-
1
post bx_block_seo_setting_seo_settings_url,
-
params: invalid_attributes
-
}.to change(BxBlockSeoSetting::SeoSetting, :count).by(0)
-
end
-
-
1
it "renders a JSON response with errors for the new seo_setting" do
-
1
post bx_block_seo_setting_seo_settings_url,
-
params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe "PATCH /update" do
-
1
context "with valid parameters" do
-
1
let(:new_attributes) {
-
{
-
1
"data": {
-
"attributes": {
-
"meta_description": "ante blandit scelerisque ac placerat purus.Proin sed felis sit amet"
-
}
-
}
-
}
-
}
-
-
-
1
it "renders a JSON response with the seo_setting" do
-
1
patch bx_block_seo_setting_seo_setting_url(@seo_setting),
-
params: new_attributes
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
context "with invalid parameters" do
-
1
it "renders a JSON response with errors for the seo_setting" do
-
1
patch bx_block_seo_setting_seo_setting_url(@seo_setting),
-
params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe "DELETE /destroy" do
-
1
it "destroys the requested seo_setting" do
-
1
expect {
-
1
delete bx_block_seo_setting_seo_setting_url(@seo_setting)
-
}.to change(BxBlockSeoSetting::SeoSetting, :count).by(-1)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::OrdersController, type: :controller do
-
1
include ActiveJob::TestHelper
-
1
before do
-
28
@customer = FactoryBot.create(:account, user_type: 'buyer')
-
28
@token_buyer = BuilderJsonWebToken.encode(@customer.id, token_type: 'login')
-
28
@order_status = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'On going')
-
28
@order_status_completed = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Completed')
-
28
@order_status_shipped = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Shipped')
-
28
@order_status_ordered = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Ordered')
-
28
@order_status_delivered = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Delivered')
-
28
@order_status_return = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Return')
-
28
@order = create(:shopping_cart_order, order_placed_at: Time.current, customer: @customer, order_status: @order_status)
-
28
@seller = FactoryBot.create(:account, company_or_store_name: "byezzy", user_type: 'seller')
-
28
@token_seller = BuilderJsonWebToken.encode(@seller.id, token_type: 'login')
-
28
@catalogue = create(:catalogue, seller: @seller)
-
28
@product_content = create(:product_content, catalogue: @catalogue)
-
28
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order, accepted: false )
-
28
@order_1 = create(:shopping_cart_order, order_placed_at: 5.days.ago, customer: @customer, order_status: @order_status)
-
28
@order_item_1 = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order_1)
-
28
@coupon = create(:coupon)
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns the order detail' do
-
1
get :show, params: { id: @order.id, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['id']).to eq(@order.id.to_s)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['id']).to eq(@order_item.id.to_s)
-
end
-
-
1
it 'returns the order details and updates order items if status if on_going or scheduled' do
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:assign_price_to_order_item).and_call_original
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:save).and_call_original
-
-
1
get :show, params: { id: @order.id, token: @token_buyer }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['attributes']['final_price']).to eq(@order.final_price)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['price']).to eq(@order_item.price)
-
-
end
-
-
1
it 'returns the order details and updates order items if catalogue has offers' do
-
1
offer_order = create(:shopping_cart_order, customer: @customer, order_status: @order_status)
-
1
offer_catalogue = create(:catalogue, seller: @seller)
-
1
offer_catalogue_prod_cont = create(:product_content, catalogue: offer_catalogue)
-
1
offer = create(:catalogue_offer, catalogue: offer_catalogue, status: true)
-
1
offer_order_item = create(:shopping_cart_order_item, catalogue: offer_catalogue, order: offer_order)
-
-
1
get :show, params: { id: offer_order.id, token: @token_buyer }
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['price']).to eq(offer.sale_price)
-
1
expect(response_body['data']['attributes']['discount']).to eq(offer_order.discount)
-
-
end
-
-
1
it 'returns the order details and updates order items if catalogue as deal' do
-
1
deal_order = create(:shopping_cart_order, customer: @customer, order_status: @order_status)
-
1
deal_catalogue = create(:catalogue, seller: @seller)
-
1
deal = create(:deal)
-
1
seller_catalogue = create(:deal_catalogue, deal: deal, catalogue: deal_catalogue, seller: @seller, status: 1 )
-
1
offer_order_item = create(:shopping_cart_order_item, catalogue: deal_catalogue, order: deal_order)
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:assign_price_to_order_item).and_call_original
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:assign_discount_to_order).and_call_original
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:calculate_final_price).and_call_original
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:calculate_final_discount_price).and_call_original
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:save).and_call_original
-
-
1
get :show, params: { id: deal_order.id, token: @token_buyer }
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['price']).to eq(seller_catalogue.current_offer_price)
-
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
-
1
it 'updates the order status ordered' do
-
1
user_address = create(:user_delivery_address, account: @customer)
-
1
@order.update(address_id: user_address.id)
-
1
allow_any_instance_of(BxBlockShoppingCart::Order).to receive(:update_shipping_address).and_call_original
-
-
1
patch :update, params: { id: @order.id, orders: { status: @order_status_ordered.name, order_item_id: @order_item.id }, token: @token_buyer }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['item']['catalogue']['data']['attributes']['purchased_count']).to eq(@order.catalogues.first.purchased_count)
-
1
expect(response_body['data']['attributes']['shipping_address']['data']['attributes']['address_status']).to eq('ordered')
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['item']['catalogue']['data']['attributes']['parent_catalogue_id']).to be_present
-
end
-
-
1
it 'updates the order status ordered send mail to seller and buyer' do
-
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order.id, orders: { status: @order_status_ordered.name, order_item_id: @order_item.id }, token: @token_buyer }
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(3)
-
-
end
-
-
1
it 'updates the order status deliveried send mail to seller and buyer' do
-
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order.id, orders: { status: @order_status_delivered.name, order_item_id: @order_item.id }, token: @token_buyer }
-
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(3)
-
end
-
-
1
it 'updates the order status shipped send mail to seller and buyer' do
-
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order.id, orders: { status: @order_status_shipped.name, order_item_id: @order_item.id }, token: @token_buyer }
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(2)
-
end
-
-
1
it 'updates the order status' do
-
-
1
patch :update, params: { id: @order.id, orders: { status: @order_status_completed.name, order_item_id: @order_item.id }, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['attributes']['order_status']['data']['attributes']['name']).to eq("Completed")
-
1
data = JSON.parse(response.body)
-
1
expect(data[:coupon_code]).to eq(nil)
-
1
expect(BxBlockActivitylog::ActivityLog.find_by(user_email: @customer.email).action).to eq("Order Status updated")
-
end
-
-
1
it 'invalid if order_status' do
-
1
patch :update, params: { id: @order.id, orders: { status: 'invalid_status', order_item_id: @order_item.id }, token: @token_seller }
-
1
expect(response_body['errors']).to eq('Invalid order or order status')
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
-
1
describe 'post #apply_coupon_to_order' do
-
1
it 'apply the coupon' do
-
1
post :apply_coupon_to_order, params: { id: @order.id, token: @token_buyer, coupon_code: @coupon.code }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['attributes']['coupon_code']['data']['attributes']['code']).to eq(@coupon.code)
-
1
expect(response_body['message']).to eq("coupon_code applied")
-
end
-
-
1
it 'returns errors if the apply coupon fails' do
-
1
post :apply_coupon_to_order, params: { id: @order.id, token: @token_buyer, coupon_code: '' }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body).to include('errors')
-
end
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a list of orders #index' do
-
1
@order.update(order_status_id: @order_status_completed.id)
-
1
get :index, params: { token: @token_buyer, filter_by: @order_status_completed.name, per_page: 10, page: 1 }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['orders'].last['order_details']['total_fees']).to eq(@order.total_fees)
-
1
expect(response_body['orders'].last['order_details']['order_item_details']).to have_key('selected_product_variant')
-
1
expect(response_body['orders'].last['order_details']).to have_key('order_item_details')
-
1
expect(response_body).to have_key('total_count')
-
end
-
-
1
it 'returns a list of orders #index filter' do
-
1
@order.update(order_status_id: @order_status_completed.id)
-
1
get :index, params: { token: @token_buyer, filter_by: 'history' }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['orders'].last['order_details']['id']).to eq(@order.id)
-
end
-
-
1
it 'returns a list of orders #index filter array' do
-
1
@order.update(order_status_id: @order_status_completed.id)
-
1
get :index, params: { token: @token_buyer, filter_by: [@order_status_completed.name] }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['orders'].last['order_details']['id']).to eq(@order.id)
-
end
-
-
1
it 'returns a list of orders with shippied address' do
-
1
user_address = create(:user_delivery_address, account: @customer)
-
1
@order.update(address_id: user_address.id)
-
1
@order.update(order_status_id: @order_status_ordered.id)
-
1
allow_any_instance_of(BxBlockShoppingCart::Order).to receive(:update_shipping_address).and_call_original
-
-
1
get :index, params: {token: @token_buyer, filter_by: [@order_status_ordered.name]}
-
1
@order.reload
-
-
1
expect(response_body['orders'].last['order_details']['shipping_address']['data']['attributes']['address_status']).to eq(@order_status_ordered.status)
-
end
-
-
1
it 'returns a list of orders by order item status' do
-
1
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
1
@order_item.update(order_status_id: @order_status_return.id)
-
-
1
get :index, params: {token: @token_buyer, order_item_status: [@order_status_return.name]}
-
1
@order.reload
-
-
1
expect(response_body['orders'].last['order_details']['order_item_details']['order_status']['data']['attributes']['name']).to eq(@order_status_return.name)
-
end
-
end
-
-
1
describe 'GET #seller_orders' do
-
1
it 'returns a list of seller orders' do
-
1
@order_1.update(order_status: @order_status_shipped)
-
1
get :seller_orders, params: { token: @token_seller}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body[0]['order_id']).to eq(@order_1.id - 1)
-
1
expect(response_body[0]['total_fees']).to eq(@order_1.total_fees)
-
1
expect(response_body[0]['discount']).to eq(@order_1.discount.to_s)
-
end
-
-
1
it 'returns a list of seller orders by sort date_latest' do
-
1
get :seller_orders, params: { token: @token_seller, sort_by: 'date_latest' }
-
-
1
expect(response).to have_http_status(:ok)
-
# expect(response_body[0]['id']).to eq(@order_1.id)
-
1
expect(response_body[0]['total_fees']).to eq(@order_1.total_fees)
-
1
expect(response_body[0]['discount']).to eq(@order_1.discount.to_s)
-
end
-
-
1
it 'returns a list of seller orders by sort date_oldest' do
-
1
get :seller_orders, params: { token: @token_seller, sort_by: 'date_oldest' }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a list of seller orders by sort product_name_AZ' do
-
1
get :seller_orders, params: { token: @token_seller, sort_by: 'product_name_AZ' }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a list of seller orders by sort product_name_ZA' do
-
1
get :seller_orders, params: { token: @token_seller, sort_by: 'product_name_ZA' }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a list of seller orders by search query' do
-
1
get :seller_orders, params: { token: @token_seller, search_query: "#{@order.order_number}" }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body[0]['order_id']).to eq(@order.id)
-
1
expect(response_body[0]['total_fees']).to eq(@order.total_fees)
-
1
expect(response_body[0]['discount']).to eq(@order.discount.to_s)
-
end
-
-
1
it 'returns a no seller orders' do
-
1
get :seller_orders, params: { token: @token_seller, filter_by: 'inv_status' }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to eq('No order present ')
-
end
-
end
-
-
1
describe 'GET #show_seller_orders' do
-
1
it 'returns a show of seller orders' do
-
1
get :show_seller_order, params: { token: @token_seller, id: @order_1.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body[0]['order_id']).to eq(@order_1.id)
-
1
expect(response_body[0]['total_fees']).to eq(@order_1.total_fees)
-
1
expect(response_body[0]['discount']).to eq(@order_1.discount.to_s)
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the order' do
-
1
order = create(:shopping_cart_order, customer: @customer, order_status: @order_status)
-
-
1
expect do
-
1
delete :destroy, params: { id: order.id, token: @token_seller }
-
2
end.to change { BxBlockShoppingCart::Order.count }.by(-1)
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to eq('order destroyed')
-
end
-
end
-
-
1
describe 'DELETE #destroy_all_orders' do
-
1
it 'destroys all orders and associated items' do
-
1
order_de = create_list(:shopping_cart_order, 3, customer: @customer, order_status: @order_status)
-
1
create_list(:shopping_cart_order_item, 5, catalogue: @catalogue, order: order_de.first)
-
-
1
delete :destroy_all_orders, params: { token: @token_seller}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to eq('Destroyed all orders')
-
end
-
-
1
it 'returns no orders present if no orders found' do
-
1
BxBlockShoppingCart::Order.destroy_all
-
1
delete :destroy_all_orders, params: { token: @token_seller}
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['message']).to eq('No orders present')
-
end
-
end
-
-
1
private
-
-
1
def response_body
-
38
JSON.parse(response.body)
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::OrderItemsController, type: :controller do
-
1
include ActiveJob::TestHelper
-
1
before do
-
25
@customer = FactoryBot.create(:account, user_type: 'buyer')
-
25
@customer_2 = FactoryBot.create(:account, user_type: 'buyer', first_name: "user")
-
25
@account = FactoryBot.create(:account, user_type: 'seller')
-
25
@token = BuilderJsonWebToken.encode(@customer.id, token_type: 'login')
-
25
@order_status = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Return')
-
25
@order_status_ordered = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Ordered')
-
25
@order_statusr = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Refunded')
-
25
@order_status_rejected = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Rejected')
-
25
@order = create(:shopping_cart_order, customer: @customer)
-
25
@catalogue = create(:catalogue, seller: @account)
-
25
@catalogue_variant = create(:catalogue_variant, seller: @account)
-
25
@product_variant_group = create(:product_variant_group, catalogue: @catalogue)
-
25
@group_attributes = create_list(:group_attribute, 2, product_variant_group: @product_variant_group)
-
end
-
-
1
describe 'POST #create' do
-
1
context 'when creating a new order item' do
-
1
it 'creates a new order item for the customer' do
-
1
post :create, params: { token: @token, order_items: { catalogue_id: @catalogue.id, quantity: 2, product_variant_group_id: @product_variant_group.id } }
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['item']['catalogue']['data']['id']).to eq(@catalogue.id.to_s)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['quantity']).to eq(@order.order_items.last.quantity)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['item']['selected_product_variant']['id']).to eq(@product_variant_group.id)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['item']['selected_product_variant']['group_attributes'][0]['attribute_name']).to eq(@product_variant_group.group_attributes.first.attribute_name)
-
end
-
end
-
-
1
context 'when updating an existing order item' do
-
1
before do
-
3
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
end
-
-
1
it 'updates the quantity of the existing order item in shopping_cart' do
-
1
post :create, params: { token: @token, order_items: { catalogue_id: @catalogue.id, quantity: 3, shopping_cart: true } }
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['item']['catalogue']['data']['id']).to eq(@catalogue.id.to_s)
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['quantity']).to eq(3)
-
end
-
-
1
it 'returns a error for quantity exceeding' do
-
1
post :create, params: { token: @token, order_items: { catalogue_id: @catalogue.id, quantity: 6, shopping_cart: true } }
-
1
expect(response_body).to include('data')
-
end
-
-
1
it 'updates the quantity of the existing order item' do
-
1
post :create, params: { token: @token, order_items: { catalogue_id: @catalogue.id, quantity: 2} }
-
-
1
expect(response_body['data']['attributes']['order_items']['data'][0]['attributes']['quantity']).to eq(4)
-
end
-
end
-
-
1
context 'when order item creation fails' do
-
1
it 'returns errors if creation fails' do
-
1
post :create, params: { token: @token, order_items: { catalogue_id: nil, quantity: 2 } }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body).to include('errors')
-
end
-
end
-
end
-
-
1
describe 'POST #guest_user_order' do
-
1
context 'guest_user_order when creating a new order item' do
-
1
it 'guest_user_order creates a new order item for the customer' do
-
1
post :guest_user_order, params: { token: @token, order_items: [{ catalogue_id: @catalogue.id, quantity: 2, product_variant_group_id: @product_variant_group.id }] }
-
-
1
expect(response).to have_http_status(:created)
-
1
expect(response_body['order']['data']['attributes']['order_items']['data'][0]['attributes']['item']['catalogue']['data']['id']).to eq(@catalogue.id.to_s)
-
1
expect(response_body['order']['data']['attributes']['order_items']['data'][0]['attributes']['quantity']).to eq(@order.order_items.last.quantity)
-
1
expect(response_body['message']).to eq('Order items added successfully')
-
end
-
end
-
-
1
context 'guest_user_order when updating an existing order item' do
-
1
before do
-
2
@order_item1 = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
end
-
-
1
it 'guest_user_order updates the quantity of the existing order item' do
-
1
post :guest_user_order, params: { token: @token, order_items: [{ catalogue_id: @catalogue.id, quantity: 2}] }
-
-
1
expect(response_body['order']['data']['attributes']['order_items']['data'][0]['attributes']['quantity']).to eq(@order_item1.reload.quantity)
-
end
-
-
1
it 'guest_user_order updates the quantity of the existing order item which exceeds the stocks' do
-
1
post :guest_user_order, params: { token: @token, order_items: [{ catalogue_id: @catalogue.id, quantity: 10}] }
-
-
1
expect(response_body['order']['data']['attributes']['order_items']['data'][0]['attributes']['quantity']).to eq(@catalogue.stocks)
-
end
-
end
-
-
1
context 'guest_user_order when order item creation fails' do
-
1
it 'guest_user_order returns errors if creation fails' do
-
1
post :guest_user_order, params: { token: @token, order_items: [] }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body['message']).to include('Provide valid products')
-
end
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
before do
-
3
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
end
-
-
1
it 'destroys an order item' do
-
1
delete :destroy, params: { token: @token, id: @order_item.id }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body).to include('message' => 'Order items deleted successfully!')
-
end
-
-
1
it 'returns not found if the order item does not exist' do
-
1
delete :destroy, params: { token: @token, id: 999 }
-
-
1
expect(response).to have_http_status(:not_found)
-
end
-
-
1
context 'when order item deletion fails' do
-
1
it 'returns errors if deletion fails' do
-
1
allow_any_instance_of(BxBlockShoppingCart::OrderItem).to receive(:destroy).and_return(false)
-
-
1
delete :destroy, params: { token: @token, id: @order_item.id }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response_body).to include('errors')
-
end
-
end
-
end
-
-
1
describe 'PATCH #update' do
-
1
before do
-
6
@order_1 = create(:shopping_cart_order, customer: @customer)
-
6
@order_statusc = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Cancelled')
-
6
@order_statusin = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Refund Initiated')
-
6
@order_statuspick = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Pickup Initiated')
-
6
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order_1)
-
end
-
1
it 'updates the order status' do
-
-
1
patch :update, params: { id: @order_item.id, order_status_id: @order_statusc.id, token: @token }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['data']['attributes']['order_status']['data']['attributes']['name']).to eq(@order_statusc.name)
-
end
-
-
1
it 'updates the order status to return send mail to seller' do
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order_item.id, order_status_id: @order_status.id, token: @token }
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(2)
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'updates the order status to pick up send mail to seller or buyer' do
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order_item.id, order_status_id: @order_statuspick.id, token: @token }
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(1)
-
end
-
-
1
it 'updates the order status to return Initiated send mail to seller or buyer' do
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order_item.id, order_status_id: @order_statusin.id, token: @token }
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(2)
-
end
-
-
1
it 'updates the order status to refunded send mail to seller' do
-
1
expect {
-
1
perform_enqueued_jobs do
-
1
patch :update, params: { id: @order_item.id, order_status_id: @order_statusr.id, token: @token }
-
end
-
2
}.to change { ActionMailer::Base.deliveries.count }.by(1)
-
end
-
-
1
it 'invalid if order_status' do
-
1
patch :update, params: { id: @order_item.id, order_status_id: 'invalid_status', token: @token }
-
1
expect(response_body['message']).to eq("Order status not found")
-
1
expect(response).to have_http_status(:not_found)
-
end
-
end
-
-
1
describe 'GET #seller_orders' do
-
1
before do
-
7
@order_0 = create(:shopping_cart_order, customer: @customer, order_status: @order_status)
-
7
@seller = FactoryBot.create(:account, company_or_store_name: "byezzy", user_type: 'seller')
-
7
@token_seller = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
7
@catalogue_1 = create(:catalogue, seller: @account)
-
7
@product_content = create(:product_content, catalogue: @catalogue_1)
-
7
@order_item_0 = create(:shopping_cart_order_item, catalogue: @catalogue_1, order: @order_0, order_status: @order_status)
-
7
@order_1 = create(:shopping_cart_order, customer: @customer)
-
7
@order_1.update(order_status: @order_status_ordered)
-
7
@order_1.update(order_status: @order_status)
-
7
@order_item_1 = create(:shopping_cart_order_item, catalogue: @catalogue_1, order: @order_1, order_status: @order_status_rejected)
-
7
@return_exchange_request = create(:return_exchange_request, order: @order_1, customer: @customer)
-
7
@return_reason_detail = create(:return_reason_detail, order_item: @order_item_1 )
-
end
-
-
1
it 'returns a list of seller orders' do
-
1
@order_item_1.update(order_status: @order_status_rejected)
-
1
@return_exchange_request.order_items << @order_item_1
-
1
@return_exchange_request.save
-
1
@order_item_1.reload
-
1
get :index, params: { token: @token_seller, filter_by: ['rejected'] }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['orders'][0]['order_details']['id']).to eq(@order_1.id)
-
1
expect(response_body['orders'][0]['order_details']['total_fees']).to eq(@order_1.total_fees)
-
1
expect(response_body['orders'][0]['order_details']['discount']).to eq(@order_1.discount)
-
1
expect(response_body['orders'][0]['order_details']['time_passed_since_order_placed']).to eq(distance_of_time_in_words(@order_1.order_placed_at, Time.now))
-
1
expect(response_body['orders'][0]['order_details']['order_item_details']['id']).to eq(@order_item_1.id)
-
1
expect(response_body['orders'][0]['order_details']['return_exchange_requests'][0]['request_reason']).to eq(@return_exchange_request.request_reason)
-
1
expect(response_body['orders'][0]['order_details']['return_reason_details'][0]['details']).to eq(@return_reason_detail.details)
-
end
-
-
1
it 'returns a list of seller orders by sort date_latest' do
-
1
get :index, params: { token: @token_seller, sort_by: 'date_latest', filter_by: ['rejected','review'] }
-
-
1
expect(response).to have_http_status(:ok)
-
# expect(response_body[0]['id']).to eq(@order_1.id)
-
1
expect(response_body['orders'][0]['order_details']['total_fees']).to eq(@order_1.total_fees)
-
1
expect(response_body['orders'][0]['order_details']['discount']).to eq(@order_1.discount)
-
end
-
-
1
it 'returns a list of seller orders by sort date_oldest' do
-
1
get :index, params: { token: @token_seller, sort_by: 'date_oldest', filter_by: ['rejected','review'] }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a list of seller orders by sort product_name_AZ' do
-
1
get :index, params: { token: @token_seller, sort_by: 'product_name_AZ', filter_by: ['rejected','review'] }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a list of seller orders by sort product_name_ZA' do
-
1
get :index, params: { token: @token_seller, sort_by: 'product_name_ZA', filter_by: ['rejected','review'] }
-
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'returns a list of seller orders by search query' do
-
1
get :index, params: { token: @token_seller, search_query: @catalogue_1.sku, filter_by: ['rejected','review'] }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['orders'][0]['order_details']['id']).to eq(@order_1.id)
-
1
expect(response_body['orders'][0]['order_details']['total_fees']).to eq(@order_1.total_fees)
-
1
expect(response_body['orders'][0]['order_details']['discount']).to eq(@order_1.discount)
-
end
-
-
1
it 'returns a no seller orders' do
-
1
get :index, params: { token: @token_seller, filter_by: ['inv_status'] }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(response_body['orders']['message']).to eq('No return orders')
-
end
-
end
-
-
1
private
-
-
1
def response_body
-
32
JSON.parse(response.body)
-
end
-
end
-
# frozen_string_literal: true
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::ReturnExchangeRequestsController, type: :controller do
-
7
let(:customer) { create(:account, user_type: 'buyer') }
-
7
let(:token) { BuilderJsonWebToken.encode(customer.id, token_type: 'login') }
-
7
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Delivered') }
-
7
let(:order) { create(:shopping_cart_order, customer: customer) }
-
2
let(:order_item) { create(:shopping_cart_order_item, order: order) }
-
-
1
before do
-
6
order.update(order_status: order_status)
-
end
-
3
let(:return_exchange_request) { create(:return_exchange_request, order: order, customer: customer) }
-
1
let(:valid_attributes) do
-
{
-
1
order_number: order.order_number,
-
request_type: 'return',
-
request_reason: 'Defective product',
-
description: 'The product is defective and needs to be returned',
-
order_item_ids: [order_item.id]
-
}
-
end
-
1
let(:invalid_attributes) do
-
2
{ order_number: order.order_number, request_type: nil, request_reason: nil, description: nil }
-
end
-
-
1
describe 'GET #index' do
-
1
it 'returns a success response' do
-
1
return_exchange_request = create(:return_exchange_request, customer: customer, order: order)
-
1
get :index, params: { token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)[0]['id']).to eq(return_exchange_request.id)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'returns a success response' do
-
1
get :show, params: { id: return_exchange_request.id, token: token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['id']).to eq(return_exchange_request.id)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'with valid params' do
-
1
it 'creates a new ReturnExchangeRequest' do
-
1
expect do
-
1
post :create, params: { token: token, return_exchange_request: valid_attributes }
-
end.to change(BxBlockShoppingCart::ReturnExchangeRequest, :count).by(1)
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'with invalid params' do
-
1
it 'renders a JSON response with errors for the new return_exchange_request' do
-
1
post :create, params: { token: token, return_exchange_request: invalid_attributes }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
-
1
context 'with invalid order' do
-
1
it 'renders a JSON response with not_found for the new return_exchange_request' do
-
1
invalid_attributes[:order_number] = '345678'
-
1
post :create, params: { token: token, return_exchange_request: invalid_attributes }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['error']).to eq('Order not found')
-
end
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the requested return_exchange_request' do
-
1
delete :destroy, params: { token: token, id: return_exchange_request.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::ReturnReasonDetailsController, type: :controller do
-
1
before do
-
7
@customer = FactoryBot.create(:account, user_type: 'buyer')
-
7
@order_status = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Return')
-
7
@order = create(:shopping_cart_order, customer: @customer, order_status: @order_status)
-
7
@seller = FactoryBot.create(:account, company_or_store_name: "byezzy", user_type: 'seller')
-
7
@token_seller = BuilderJsonWebToken.encode(@seller.id, token_type: 'login')
-
7
@catalogue = create(:catalogue, seller: @seller)
-
7
@product_content = create(:product_content, catalogue: @catalogue)
-
7
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order, order_status: @order_status)
-
7
@return_reason_detail = create(:return_reason_detail, order_item: @order_item )
-
end
-
1
let(:valid_attributes) do
-
{
-
1
title: 'Return Reason Title',
-
details: 'Return Reason Details',
-
shopping_cart_order_item_id: @order_item.id,
-
reason_type: 'return_reason'
-
}
-
end
-
-
1
describe 'GET #index' do
-
1
it 'index returns a success response' do
-
1
return_reason_detail_1 = create(:return_reason_detail, order_item: @order_item)
-
1
get :index, params: {token: @token_seller}
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)[0]['id']).to eq(return_reason_detail_1.id)
-
end
-
end
-
-
1
describe 'GET #show' do
-
1
it 'show returns a success response' do
-
1
get :index, params: {token: @token_seller, id: @return_reason_detail.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)[0]['id']).to eq(@return_reason_detail.id)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'create with valid params' do
-
1
it 'creates a new ReturnReasonDetail' do
-
1
expect do
-
1
post :create, params: { return_reason_detail: valid_attributes, token: @token_seller }
-
end.to change(BxBlockShoppingCart::ReturnReasonDetail, :count).by(1)
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context 'create with invalid params' do
-
1
it 'create renders a JSON response with errors for the new return_reason_detail' do
-
1
post :create, params: {token: @token_seller, return_reason_detail: { title: nil } }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
context 'update with valid params' do
-
1
let(:new_attributes) do
-
1
{ title: 'New Title' }
-
end
-
-
1
it 'update updates the requested return_reason_detail' do
-
1
put :update, params: {token: @token_seller, id: @return_reason_detail.id, return_reason_detail: new_attributes }
-
1
@return_reason_detail.reload
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['title']).to eq(@return_reason_detail.title)
-
end
-
end
-
-
1
context 'update with invalid params' do
-
1
it 'update renders a JSON response with errors for the return_reason_detail' do
-
1
put :update, params: {token: @token_seller, id: @return_reason_detail.id, return_reason_detail: { title: nil } }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the requested return_reason_detail' do
-
1
expect do
-
1
delete :destroy, params: {token: @token_seller, id: @return_reason_detail.to_param }
-
end.to change(BxBlockShoppingCart::ReturnReasonDetail, :count).by(-1)
-
1
expect(JSON.parse(response.body)['message']).to eq('return reason destroy')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::ShippedOrderDetailsController, type: :controller do
-
1
before do
-
6
@customer = FactoryBot.create(:account, user_type: 'buyer')
-
6
@order_status = BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Shipped')
-
6
@order = create(:shopping_cart_order, customer: @customer, order_status: @order_status)
-
6
@seller = FactoryBot.create(:account, company_or_store_name: "byezzy", user_type: 'seller')
-
6
@token_seller = BuilderJsonWebToken.encode(@seller.id, token_type: 'login')
-
6
@catalogue = create(:catalogue, seller: @seller)
-
6
@product_content = create(:product_content, catalogue: @catalogue)
-
6
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order, order_status: @order_status)
-
6
@shipped_order_detail = create(:shipped_order_detail, order: @order, order_item_id: @order_item.id )
-
end
-
1
let(:valid_attributes) do
-
{
-
1
"shipping_details": "Tracking ids",
-
"courier_name": "courier name",
-
"tracking_number": "track12345number"
-
}
-
end
-
-
1
describe 'GET #show' do
-
1
it 'show returns a success response' do
-
1
get :show, params: {token: @token_seller, id: @shipped_order_detail.id, order_id: @order.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['id']).to eq(@shipped_order_detail.id)
-
end
-
end
-
-
1
describe 'POST #create' do
-
1
context 'create with valid params and multiple order_item_ids' do
-
1
it 'creates multiple shipped_order_details and returns the last one' do
-
# Create two order items
-
1
order_item_1 = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order, order_status: @order_status)
-
1
order_item_2 = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order, order_status: @order_status)
-
-
1
order_item_ids = [order_item_1.id, order_item_2.id]
-
-
1
expect do
-
1
post :create, params: {
-
order_id: @order.id,
-
token: @token_seller,
-
shipped_order_detail: valid_attributes.merge(order_item_id: order_item_ids)
-
}
-
end.to change(BxBlockShoppingCart::ShippedOrderDetail, :count).by(2)
-
-
1
expect(response).to have_http_status(:created)
-
1
json_response = JSON.parse(response.body)
-
1
expect(json_response["order_item_id"]).to eq(order_item_2.id)
-
end
-
end
-
-
1
context 'create with invalid params' do
-
1
it 'create renders a JSON response with errors for the new shipped_order_detail' do
-
1
post :create, params: {
-
token: @token_seller,
-
order_id: @order.id,
-
shipped_order_detail: { courier_name: nil }
-
}
-
1
parsed_response = JSON.parse(response.body)
-
# byebug
-
# expect(parsed_response["courier_name"]).to include("can't be blank")
-
# expect(parsed_response["tracking_number"]).to include("can't be blank")
-
# expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe 'PUT #update' do
-
1
context 'update with valid params' do
-
1
let(:new_attributes) do
-
1
{ shipping_details: 'update details' }
-
end
-
-
1
it 'update updates the requested shipped_order_detail' do
-
1
put :update, params: {token: @token_seller, order_id: @order.id, id: @shipped_order_detail.id, shipped_order_detail: new_attributes }
-
1
@shipped_order_detail.reload
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['shipping_details']).to eq(@shipped_order_detail.shipping_details)
-
end
-
end
-
-
1
context 'update with invalid params' do
-
1
it 'update renders a JSON response with errors for the shipped_order_detail' do
-
1
put :update, params: {token: @token_seller, order_id: @order.id, id: @shipped_order_detail.id, shipped_order_detail: { tracking_number: nil } }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
end
-
end
-
end
-
-
1
describe 'DELETE #destroy' do
-
1
it 'destroys the requested shipped_order_detail' do
-
1
delete :destroy, params: {token: @token_seller, order_id: @order.id, id: @shipped_order_detail.id }
-
1
expect(JSON.parse(response.body)['message']).to eq("shipped order detail destroyed")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::TelrPaymentsController, type: :controller do
-
-
1
before do
-
4
@customer = FactoryBot.create(:account, user_type: 'buyer')
-
4
@customer_2 = FactoryBot.create(:account, user_type: 'buyer')
-
4
@token_buyer = BuilderJsonWebToken.encode(@customer.id, token_type: 'login')
-
4
@token_buyer_2 = BuilderJsonWebToken.encode(@customer.id, token_type: 'login')
-
4
@order_status = BxBlockOrderManagement::OrderStatus.find_by(name: 'On Going') || BxBlockOrderManagement::OrderStatus.create(name: 'On going')
-
4
@order_status_ordered = BxBlockOrderManagement::OrderStatus.find_by(name: 'Ordered') || BxBlockOrderManagement::OrderStatus.create(name: 'Ordered')
-
4
@order = create(:shopping_cart_order, customer: @customer)
-
4
@order_2 = create(:shopping_cart_order, customer: @customer_2)
-
4
@order.update(order_status: @order_status)
-
4
@seller = FactoryBot.create(:account, company_or_store_name: "byezzy", user_type: 'seller')
-
4
@catalogue = create(:catalogue, seller: @seller)
-
4
@product_content = create(:product_content, catalogue: @catalogue)
-
4
@order_item = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order)
-
4
@order_item_2 = create(:shopping_cart_order_item, catalogue: @catalogue, order: @order_2)
-
end
-
-
1
describe 'POST #create' do
-
1
it 'creates a new order status and updates the order with the transaction id' do
-
-
1
stub_request(:post, "https://secure.telr.com/gateway/order.json")
-
.to_return(body: { 'order' => { 'ref' => '123456789' } }.to_json, status: 200)
-
-
# allow(controller).to receive(:post_gateway).and_return(({ 'order': { 'ref': '123456789' } }).to_json)
-
-
1
post :create, params: { order_id: @order.id, final_price: 100, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(@order.reload.transaction_id).to eq('123456789')
-
end
-
-
1
it 'renders an error if the order is already processed' do
-
1
@order.update(order_status: @order_status_ordered)
-
-
1
post :create, params: { order_id: @order.id, final_price: @order.final_price, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors']).to eq('On going orders only accepted')
-
end
-
end
-
-
1
describe 'GET #show_or_check' do
-
1
it 'returns the response from the payment gateway' do
-
1
stub_request(:post, "https://secure.telr.com/gateway/order.json")
-
.to_return(body: { 'status' => 'success' }.to_json, status: 200)
-
-
# allow(controller).to receive(:post_gateway).and_return({ 'status' => 'success' })
-
-
1
get :show_or_check, params: { order_id: @order.id, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['status']).to eq('success')
-
end
-
end
-
-
1
describe 'Post #payment failed notification' do
-
1
it 'returns the response notification failed' do
-
1
post :payment_failed_notification, params: { order_id: @order.id, token: @token_buyer }
-
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)['message']).to eq('Payment failed notification sent successfully.')
-
1
expect(ActionMailer::Base.deliveries.count).to eq(1)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
1
RSpec.describe BxBlockStoreManagement::StoresController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@brand = create(:brand)
-
1
@store = create(:store, approve: true)
-
1
@seller_account = create(:account, user_type: 'seller')
-
1
@seller_token = BuilderJsonWebToken.encode(@seller_account.id, token_type: 'login')
-
1
@store_params = attributes_for(:store)
-
end
-
-
1
describe 'GET index' do
-
1
it 'returns a list of stores' do
-
1
get :index, params: {token: @token}
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockStoreManagement::Store.count)
-
end
-
end
-
-
1
describe 'GET index_approved_stores' do
-
1
it 'returns a list of approved stores' do
-
1
create(:store, approve: true)
-
1
create(:store, approve: false)
-
1
get :index_approved_stores, params: { token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data'].length).to eq(BxBlockStoreManagement::Store.where(approve: true).count)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'returns a specific store' do
-
1
get :show, params: { id: @store.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data']['id']).to eq(@store.id.to_s)
-
1
expect(parsed_response["data"]["attributes"]).to have_key("brand_trade_certificate")
-
end
-
-
1
it 'returns not found if the store does not exist' do
-
1
get :show, params: { id: '0' , token: @token}
-
1
expect(response).to have_http_status(:not_found)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq("Store with id 0 doesn't exists")
-
end
-
end
-
-
1
describe 'POST create' do
-
1
it 'creates a new store' do
-
1
post :create, params: @store_params.merge({token: @token,brand_id: @brand.id})
-
1
expect(response).to have_http_status(:created)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data']['attributes']['store_name']).to eq(@store_params[:store_name])
-
end
-
-
1
it 'returns unprocessable entity with errors if store creation fails' do
-
1
post :create, params: {token: @token}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors']).to include("Store year can't be blank")
-
end
-
end
-
-
1
describe 'PATCH update' do
-
1
it 'updates a specific store' do
-
1
new_store_name = 'New Store Name'
-
1
patch :update, params: { id: @store.id, store_name: new_store_name, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
@store.reload
-
1
expect(@store.store_name).to eq(new_store_name)
-
end
-
-
1
it 'returns unprocessable entity with errors if store update fails' do
-
1
patch :update, params: { id: @store.id, store_name: '', token: @token }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors']).to include("Store name can't be blank")
-
end
-
end
-
-
1
describe 'DELETE destroy' do
-
1
it 'deletes a specific store' do
-
1
delete :destroy, params: { id: @store.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(BxBlockStoreManagement::Store.exists?(@store.id)).to be_falsey
-
end
-
-
1
it 'returns not found if the store does not exist' do
-
1
delete :destroy, params: { id: '0', token: @token }
-
1
expect(response).to have_http_status(:not_found)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq("Store with id 0 doesn't exists")
-
end
-
end
-
-
1
describe 'GET#seller_store_listing ' do
-
1
context 'Get user stores listing' do
-
1
it 'when user type nil' do
-
1
get :seller_store_listing, params: {token: @token}
-
1
expect(response.body).to eq("{\"errors\":[{\"message\":\"You are not authorized to access stores\"}]}")
-
end
-
-
1
it 'when user type seller' do
-
1
@account.update(user_type: "seller")
-
1
get :seller_store_listing, params: {token: @token}
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
end
-
-
1
describe 'PUT#update_seller_store ' do
-
1
context "update seller's store" do
-
1
it 'when user type nil' do
-
1
put :update_seller_store, params: {token: @token, id: @store.id}
-
1
expect(response.body).to eq("{\"errors\":[{\"message\":\"You are not authorized to access stores\"}]}")
-
end
-
-
1
it 'when user type seller' do
-
1
put :update_seller_store, params: {token: @seller_token, id: @store.id, store_name: 'dummy'}
-
1
expect(response).to have_http_status(:ok)
-
end
-
-
1
it 'return error' do
-
1
put :update_seller_store, params: {token: @seller_token, id: @store.id, store_name: nil}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to eq("{\"errors\":[\"Store name can't be blank\"]}")
-
end
-
end
-
end
-
-
1
describe 'DELETE delete_seller_store' do
-
1
it "when delete seller's store" do
-
1
@store.update(account_id: @seller_account.id)
-
1
delete :delete_seller_store, params: { id: @store.id, token: @seller_token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(BxBlockStoreManagement::Store.exists?(@store.id)).to be_falsey
-
end
-
-
1
it 'when store does not exist with this seller' do
-
1
delete :delete_seller_store, params: { id: '0', token: @seller_token }
-
1
expect(response).to have_http_status(:not_found)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['message']).to eq("This store not belongs to your account or not exists with id 0")
-
end
-
end
-
-
1
describe 'POST create_seller_store' do
-
1
it 'creates a new store for seller' do
-
1
post :create_seller_store, params: @store_params.merge({token: @seller_token, brand_id: @brand.id})
-
1
expect(response).to have_http_status(:created)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['data']['attributes']['store_name']).to eq(@store_params[:store_name])
-
end
-
-
1
it 'returns unprocessable entity with errors if store creation fails' do
-
1
post :create_seller_store, params: {store_name: '', token: @seller_token}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
parsed_response = JSON.parse(response.body)
-
1
expect(parsed_response['errors']).to include("Store year can't be blank")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockStoreManagement::StoreDashboardSectionsController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account, user_type: 'seller')
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@store = create(:store)
-
1
@store_dashboard_section_banner = create(:store_dashboard_section, store: @store, section_name: 'banner', section_type: '', banner_name: "iphone")
-
1
@store_dashboard_section = create(:store_dashboard_section, store: @store, section_name: 'section_1', section_type: '1_grid_layout')
-
1
@store_section_grid = create(:store_section_grid, store: @store, grid_name: 'iphone', grid_no: 'grid_1', store_dashboard_section: @store_dashboard_section)
-
-
end
-
-
1
let(:valid_attributes) {
-
{
-
1
token: @token,
-
store_id: @store.id,
-
section_name: 'section_2',
-
section_type: '2_grids_layout',
-
store_section_grids_attributes: [
-
{ grid_name: 'oneplus', grid_no: 'grid_2' }
-
]
-
}
-
}
-
-
1
let(:invalid_attributes) {
-
{
-
2
token: @token,
-
store_id: @store.id,
-
section_name: '',
-
section_type: 'invalid_type'
-
}
-
}
-
-
1
describe "GET #index" do
-
1
it "returns a success response index" do
-
1
get :index, params: {store_id: @store.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a success response show" do
-
1
get :show, params: {store_id: @store.id, id: @store_dashboard_section_banner.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("banner_image")
-
1
expect(JSON.parse(response.body)["data"]["attributes"]['banner_url']).to eq("www.example.com")
-
end
-
end
-
-
1
describe "POST #create" do
-
1
context "with valid params create" do
-
-
1
it "renders a JSON response with the new store_dashboard_section" do
-
1
post :create, params: valid_attributes
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["section_type"]).to eq(@store.store_dashboard_sections.last.section_type)
-
end
-
end
-
-
1
context "with invalid params create" do
-
1
it "renders a JSON response with errors for the new store_dashboard_section" do
-
1
post :create, params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Section name can't be blank")
-
end
-
end
-
end
-
-
1
describe "PUT #update" do
-
1
context "with valid params update" do
-
1
let(:new_attributes) {
-
{
-
1
token: @token,
-
store_id: @store.id,
-
id: @store_dashboard_section.id,
-
store_section_grids_attributes: [
-
{ id: @store_section_grid.id, grid_name: 'oneplus update' }
-
]
-
}
-
}
-
-
1
it "updates the requested store_dashboard_section" do
-
1
put :update, params: new_attributes
-
1
@store_section_grid.reload
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["store_section_grids"][0]["data"]["attributes"]["grid_name"]).to eq(@store_section_grid.grid_name)
-
end
-
end
-
-
1
context "with invalid params update" do
-
1
it "update renders a JSON response with errors for the store_dashboard_section" do
-
1
put :update, params: invalid_attributes.merge(id: @store_dashboard_section.id)
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Section name is not included in the list")
-
end
-
end
-
end
-
-
1
describe "DELETE #destroy" do
-
1
it "delete renders a JSON response with the store_dashboard_section" do
-
1
delete :destroy, params: {token: @token, store_id: @store_dashboard_section.store_id, id: @store_dashboard_section.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Section removed")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockStoreManagement::StoreMenusController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@store = create(:store)
-
1
@image = fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg"))
-
1
@catalogues = create_list(:catalogue, 2)
-
1
@menu = create(:store_menu, store: @store, logo: @image, catalogues: @catalogues)
-
end
-
-
1
describe 'GET index' do
-
1
it 'returns a list of menus for a store' do
-
1
get :index, params: { store_id: @store.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe 'GET store_menus_list' do
-
1
it 'returns a list of menus for a store without catalogue' do
-
1
get :store_menus_list, params: { store_id: @store.id, token: @token }
-
1
expect(JSON.parse(response.body)["store_menus"][0]['id']).to eq(@menu.id)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
context 'when logo is attached' do
-
1
it 'returns a menu for a store with logo URL' do
-
1
get :show, params: { store_id: @store.id, id: @menu.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("logo")
-
end
-
end
-
-
1
context 'when logo is not attached' do
-
1
it 'returns a menu for a store without logo URL' do
-
1
get :show, params: { store_id: @store.id, id: 999, token: @token }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(response.body).to include("Menu not found")
-
end
-
end
-
end
-
-
-
1
describe 'POST create' do
-
1
it 'creates a new menu for a store' do
-
1
BxBlockStoreManagement::StoreMenu.where(position: 6, store_id: 1).delete_all
-
1
post :create, params: {catalogue_ids: @catalogues&.map(&:id), position: 6 ,store_id: @store.id, title: 'New Menu', token: @token, cover_image: @image }
-
1
expect(response).to have_http_status(201)
-
1
expect(assigns(:menu).title).to eq('New Menu')
-
1
expect(assigns(:menu).catalogues&.map(&:id)).to match_array(@catalogues&.map(&:id))
-
end
-
-
1
it 'renders errors if creation fails' do
-
1
post :create, params: { store_id: @store.id, title: nil, token: @token ,logo: @image}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include("Title can't be blank")
-
end
-
end
-
-
1
describe 'PATCH update' do
-
1
it 'updates an existing menu for a store' do
-
1
patch :update, params: {catalogue_ids: @catalogues&.map(&:id), store_id: @store.id, id: @menu.id, title: 'Updated Menu', token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(@menu.reload.title).to eq('Updated Menu')
-
1
expect(@menu.catalogues&.map(&:id)).to match_array(@catalogues&.map(&:id))
-
end
-
-
1
it 'renders errors if update fails' do
-
1
patch :update, params: { store_id: @store.id, id: @menu.id, title: nil, token: @token }
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(response.body).to include("Title can't be blank")
-
end
-
end
-
-
1
describe 'DELETE destroy' do
-
1
it 'destroys a menu for a store' do
-
1
delete :destroy, params: { store_id: @store.id, id: @menu.id , token: @token}
-
1
expect(response).to have_http_status(200)
-
1
expect(response.body).to include('Menu removed')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockStoreManagement::StoreSectionGridsController, type: :controller do
-
1
before(:all) do
-
1
@account = create(:account, user_type: 'seller')
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@store = create(:store)
-
1
@store_dashboard_section = create(:store_dashboard_section, store: @store, section_name: 'section_1', section_type: '1_grid_layout')
-
1
@store_section_grid = create(:store_section_grid, store: @store, grid_name: 'iphone', grid_no: 'grid_1', store_dashboard_section: @store_dashboard_section)
-
-
end
-
-
1
let(:valid_attributes) {
-
{
-
1
token: @token,
-
store_id: @store.id,
-
store_dashboard_section_id: @store_dashboard_section.id,
-
grid_name: 'oneplus',
-
grid_no: 'grid_2'
-
}
-
}
-
-
1
let(:invalid_attributes) {
-
{
-
2
token: @token,
-
store_id: @store.id,
-
store_dashboard_section_id: @store_dashboard_section.id,
-
grid_name: '',
-
grid_no: 'invalid_grid'
-
}
-
}
-
-
1
describe "GET #index" do
-
1
it "returns a success response index" do
-
1
get :index, params: { token: @token, store_id: @store.id, store_dashboard_section_id: @store_dashboard_section.id }
-
1
expect(response).to have_http_status(:ok)
-
end
-
end
-
-
1
describe "GET #show" do
-
1
it "returns a success response show" do
-
1
get :show, params: { token: @token, store_id: @store.id, store_dashboard_section_id: @store_dashboard_section.id, id: @store_section_grid.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]).to have_key("grid_image")
-
1
expect(JSON.parse(response.body)["data"]["attributes"]['grid_url']).to eq("www.example.com")
-
end
-
end
-
-
1
describe "POST #create" do
-
1
context "with valid params crate" do
-
# it "creates a new StoreSectionGrid" do
-
# expect {
-
# post :create, params: valid_attributes
-
# }.to change(BxBlockStoreManagement::StoreSectionGrid, :count).by(1)
-
# end
-
-
1
it "renders a JSON response with the new store_section_grid" do
-
1
post :create, params: valid_attributes
-
1
expect(response).to have_http_status(:created)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["grid_name"]).to eq(@store_dashboard_section.store_section_grids.last.grid_name)
-
end
-
end
-
-
1
context "with invalid params create" do
-
1
it "renders a JSON response with errors for the new store_section_grid" do
-
1
post :create, params: invalid_attributes
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Grid name can't be blank")
-
end
-
end
-
end
-
-
1
describe "PUT #update" do
-
1
context "with valid params update" do
-
1
let(:new_attributes) {
-
{
-
1
token: @token,
-
store_id: @store.id,
-
store_dashboard_section_id: @store_dashboard_section.id,
-
id: @store_section_grid.id,
-
grid_name: 'grid_3'
-
}
-
}
-
-
1
it "updates the requested store_section_grid" do
-
1
put :update, params: new_attributes
-
1
@store_section_grid.reload
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["data"]["attributes"]["grid_name"]).to eq(@store_section_grid.grid_name)
-
end
-
end
-
-
1
context "with invalid params update" do
-
1
it "update renders a JSON response with errors for the store_section_grid" do
-
1
put :update, params: invalid_attributes.merge({id: @store_section_grid.id, grid_url: "asd"})
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)["errors"]).to include("Grid url should start with 'https://' or 'www.'")
-
end
-
end
-
end
-
-
1
describe "DELETE #destroy" do
-
# it "destroys the requested store_section_grid" do
-
# expect {
-
# delete :destroy, params: { token: @token, store_id: @store.id, store_dashboard_section_id: @store_dashboard_section.id, id: @store_section_grid.id }
-
# }.to change(BxBlockStoreManagement::StoreSectionGrid, :count).by(-1)
-
# end
-
-
1
it "delete renders a JSON response with the store_section_grid" do
-
1
delete :destroy, params: { token: @token, store_id: @store.id, store_dashboard_section_id: @store_dashboard_section.id, id: @store_section_grid.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["message"]).to eq("Grid removed")
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSupport::SocialPlatformsController, type: :controller do
-
-
1
before(:all) do
-
1
BxBlockSupport::SocialPlatform.all.delete_all
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
1
@social_media = 'https://www.facebook.com/example'
-
1
@social_platform = create(:social_platform, social_media: 'Facebook', social_media_url: @social_media)
-
end
-
-
1
describe 'GET index' do
-
1
it 'returns a list of social platforms' do
-
1
get :index, params: {token: @token}
-
1
expect(response).to have_http_status(:ok)
-
-
1
expect(JSON.parse(response.body).size).to eq(BxBlockSupport::SocialPlatform.all.count)
-
1
expect(JSON.parse(response.body)[0]['social_media']).to eq('Facebook')
-
1
expect(JSON.parse(response.body)[0]['social_media_url']).to eq(@social_media)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'returns a single social platform' do
-
1
get :show, params: { id: @social_platform.id, token: @token }
-
1
expect(response).to have_http_status(:ok)
-
-
1
expect(JSON.parse(response.body)['social_media']).to eq('Facebook')
-
1
expect(JSON.parse(response.body)['social_media_url']).to eq(@social_media)
-
1
expect(JSON.parse(response.body)['social_icon']).to include(Rails.application.routes.url_helpers.rails_blob_path(@social_platform.social_icon, only_path: true))
-
end
-
-
1
it 'returns not found for an invalid ID' do
-
1
get :show, params: { id: 'invalid_id' }
-
1
expect(response).to have_http_status(:not_found)
-
1
expect(JSON.parse(response.body)['errors'][0]).to eq('Record not found')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSupport::StaticPagesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
5
let!(:support) { create(:static_page, title: "MyString", content: "MyText", status: true) }
-
-
1
describe 'GET /bx_block_support/supports' do
-
1
it 'returns a list of supports' do
-
1
get :index, params: { token: @token }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body).size).to eq(BxBlockSupport::StaticPage.where(status: true).count)
-
end
-
end
-
-
1
describe 'GET /bx_block_support/supports/:id' do
-
1
it 'returns a single support' do
-
1
get :show, params: { token: @token, id: support.id }
-
1
expect(response).to have_http_status(:ok)
-
1
expect(JSON.parse(response.body)["title"]).to eq("MyString")
-
1
expect(JSON.parse(response.body)["content"]).to eq("MyText")
-
1
expect(JSON.parse(response.body)["status"]).to eq(true)
-
end
-
-
end
-
-
1
describe 'DELETE delete_static_pages - footer' do
-
-
3
let!(:page1) { create(:static_page, title: 'page1') }
-
3
let!(:page2) { create(:static_page, title: 'page2') }
-
-
1
context 'with valid IDs' do
-
1
it 'deletes the specified pages' do
-
1
expect {
-
1
delete :delete_static_pages, params: { ids: [page1.id, page2.id] }
-
}.to change(BxBlockSupport::StaticPage, :count).by(-2)
-
-
1
expect(response).to have_http_status(:ok)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data['message']).to eq('Pages deleted successfully')
-
end
-
end
-
-
1
context 'with no IDs provided' do
-
1
it 'returns an error' do
-
1
delete :delete_static_pages, params: { ids: [] }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data['error']).to eq('No IDs provided')
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSupport::SupportDocumentsController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders a list of terms policies as JSON' do
-
1
support_document1 = create(:support_document)
-
1
support_document2 = create(:support_document)
-
-
1
get :index, params: {token: @token}
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_an(Array)
-
1
expect(response.body).to include(support_document1.page_title)
-
1
expect(response.body).to include(support_document2.content)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the details of a terms policy as JSON' do
-
1
support_document = create(:support_document)
-
-
1
get :show, params: { id: support_document.id, token: @token }
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_a(Hash)
-
1
expect(response_data['page_title']).to eq(support_document.page_title)
-
1
expect(response_data['content']).to eq(support_document.content)
-
end
-
end
-
-
1
describe 'DELETE delete_support_documents' do
-
-
3
let!(:doc1) { create(:support_document) }
-
3
let!(:doc2) { create(:support_document) }
-
-
1
context 'with valid IDs' do
-
1
it 'deletes the specified document' do
-
1
expect {
-
1
delete :delete_support_documents, params: { ids: [doc1.id, doc2.id] }
-
}.to change(BxBlockSupport::SupportDocument, :count).by(-2)
-
-
1
expect(response).to have_http_status(:ok)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data['message']).to eq('Documents deleted successfully')
-
end
-
end
-
-
1
context 'with no IDs provided' do
-
1
it 'returns an error' do
-
1
delete :delete_support_documents, params: { ids: [] }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data['error']).to eq('No IDs provided')
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSupport::SupportsController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
1
describe "POST /create" do
-
-
1
context "with valid parameters" do
-
1
it "creates a new Support" do
-
1
post :create,
-
params: { "token": @token,
-
"data": {
-
"attributes": {
-
"first_name": "test",
-
"last_name": "user",
-
"email": Faker::Internet.email,
-
"details": "ajdddddddajdsssssssssssnbcxxksaudik"
-
}
-
}
-
}
-
1
expect(response).to have_http_status(:created)
-
end
-
end
-
-
1
context "with invalid parameters" do
-
1
it "renders a JSON response with errors for the new support" do
-
1
post :create,
-
params: { "token": @token,
-
"data": {
-
"attributes": {
-
"first_name": "test",
-
"last_name": "user",
-
"email": "jdssssssssss",
-
"details": "ajdddddddajdsssssssssssnbcxxksaudik"
-
}
-
}
-
}
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
expect(JSON.parse(response.body)['errors'][0]['account']).to include("Email invalid")
-
end
-
end
-
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockTermsandconditions::PrivacyAndLegalPolicyController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders a list of privacy and legal policy as JSON' do
-
1
privacy = create(:privacy_and_legal_policy)
-
1
privacy1 = create(:privacy_and_legal_policy)
-
-
1
get :index, params: {token: @token}
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_an(Hash)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the details of a terms policy as JSON' do
-
1
privacy = create(:privacy_and_legal_policy)
-
-
1
get :show, params: { id: privacy.id, token: @token }
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_a(Hash)
-
1
expect(response_data['data']['attributes']['title']).to eq(privacy.title)
-
1
expect(response_data['data']['attributes']['content']).to eq(privacy.content)
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockTermsandconditions::SellerStaticPagesController, type: :controller do
-
-
# before(:all) do
-
# @account = create(:account)
-
# @token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
# end
-
-
1
describe 'GET index' do
-
1
it 'renders a list of seller static as JSON' do
-
1
seller_static_page1 = create(:seller_static_page, status: true)
-
1
seller_static_page2 = create(:seller_static_page, status: true)
-
-
1
get :index
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_an(Array)
-
1
expect(response.body).to include(seller_static_page1.title)
-
1
expect(response.body).to include(seller_static_page2.content)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the details of a seller static page as JSON' do
-
1
seller_static_page = create(:seller_static_page)
-
-
1
get :show, params: { id: seller_static_page.id }
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_a(Hash)
-
1
expect(response_data['title']).to eq(seller_static_page.title)
-
1
expect(response_data['content']).to eq(seller_static_page.content)
-
end
-
-
1
it 'error seller static page not found' do
-
-
1
get :show, params: { id: 999 }
-
-
1
expect(response).to have_http_status(:not_found)
-
1
response_data_1 = JSON.parse(response.body)
-
1
expect(response_data_1['errors'][0]).to eq('Record not found')
-
end
-
end
-
-
1
describe 'DELETE delete_static_pages' do
-
-
3
let!(:page1) { create(:seller_static_page, title: 'page1') }
-
3
let!(:page2) { create(:seller_static_page, title: 'page2') }
-
-
1
context 'with valid IDs' do
-
1
it 'deletes the specified pages' do
-
1
expect {
-
1
delete :delete_static_pages, params: { ids: [page1.id, page2.id] }
-
}.to change(BxBlockTermsandconditions::SellerStaticPage, :count).by(-2)
-
-
1
expect(response).to have_http_status(:ok)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data['message']).to eq('Pages deleted successfully')
-
end
-
end
-
-
1
context 'with no IDs provided' do
-
1
it 'returns an error' do
-
1
delete :delete_static_pages, params: { ids: [] }
-
-
1
expect(response).to have_http_status(:unprocessable_entity)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data['error']).to eq('No IDs provided')
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockTermsandconditions::TermsPoliciesController, type: :controller do
-
-
1
before(:all) do
-
1
@account = create(:account)
-
1
@token = BuilderJsonWebToken.encode(@account.id, token_type: 'login')
-
end
-
-
1
describe 'GET index' do
-
1
it 'renders a list of terms policies as JSON' do
-
1
terms_policy1 = create(:terms_policy)
-
1
terms_policy2 = create(:terms_policy)
-
-
1
get :index, params: {token: @token}
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_an(Array)
-
1
expect(response.body).to include(terms_policy1.page_title)
-
1
expect(response.body).to include(terms_policy2.content)
-
end
-
end
-
-
1
describe 'GET show' do
-
1
it 'renders the details of a terms policy as JSON' do
-
1
terms_policy = create(:terms_policy)
-
-
1
get :show, params: { id: terms_policy.id, token: @token }
-
-
1
expect(response).to have_http_status(:success)
-
1
response_data = JSON.parse(response.body)
-
1
expect(response_data).to be_a(Hash)
-
1
expect(response_data['page_title']).to eq(terms_policy.page_title)
-
1
expect(response_data['content']).to eq(terms_policy.content)
-
end
-
end
-
-
end
-
1
FactoryBot.define do
-
1
factory :account, class: 'AccountBlock::Account' do
-
2761
sequence(:email) { |n| Faker::Internet.unique.email(name: Faker::Lorem.characters(number: 10, min_alpha: 4)) }
-
2765
full_phone_number {"919#{rand(100...999)}#{rand(100000...999999)}"}
-
2742
password { 'Password@123' }
-
2740
first_name {"my string"}
-
2765
last_name {"my string"}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :seller_document, class: 'AccountBlock::SellerDocument' do
-
59
document_type { "Trading License or Commercial Registration" }
-
63
document_name { "MyString" }
-
3
document_files { [] }
-
63
vat_reason { "MyString" }
-
63
iban { "MyString" }
-
63
bank_address { "MyString" }
-
63
name { "MyString" }
-
63
bank_name { "MyString" }
-
63
swift_code { "MyString" }
-
27
approved { false }
-
63
rejected {false}
-
1
account
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :sms_otp, class: 'AccountBlock::SmsOtp' do
-
7
full_phone_number {"919977" + "#{rand(100000...999999)}"}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :suggestion_feedback ,class: 'AccountBlock::SuggestionFeedback'do
-
5
detail_type { "MyString" }
-
5
detail { "MyString" }
-
5
first_name { "MyString" }
-
5
last_name { "MyString" }
-
5
email { "MyString" }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :user_delivery_address, class: "AccountBlock::UserDeliveryAddress" do
-
7
first_name { "MyString" }
-
7
last_name { "MyString" }
-
7
phone_number {"9190 + #{rand(100000...999999)}"}
-
7
address_1 { "MyString" }
-
7
address_2 { "MyString" }
-
7
city { "MyString" }
-
7
zip_code { "MyString" }
-
4
is_default { false }
-
7
address_type { "MyString" }
-
7
state { "MyString" }
-
1
account
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :admin_user do
-
342
email { Faker::Internet.email }
-
342
password { 'password' }
-
342
password_confirmation { 'password' }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :activity_log, class: 'BxBlockActivitylog::ActivityLog' do
-
3
user_type {'seller'}
-
3
action {"Test action"}
-
3
accessed_at { Time.current }
-
3
details {"Created activity log"}
-
1
trait :with_account do
-
1
association :user, factory: :account
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :attribute_option ,class: 'BxBlockCatalogue::AttributeOption' do
-
8
option { Faker::Lorem.word }
-
1
variant_attribute
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :barcode, class: 'BxBlockCatalogue::Barcode' do
-
51
bar_code { Faker::Lorem.word + rand(1..10000).to_s }
-
1
catalogue
-
51
status { false }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :brand ,class: 'BxBlockCatalogue::Brand'do
-
1859
brand_name { Faker::Lorem.word + rand(1..20000).to_s + Faker::Lorem.word}
-
1859
brand_name_arabic { Faker::Lorem.word + rand(1..10000).to_s }
-
1859
brand_website {"www.#{Faker::Lorem.word}.com"}
-
1859
brand_year {rand(1900..2023)}
-
1859
brand_image {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg'))}
-
1
branding_tradmark_certificate {}
-
1856
approve { true }
-
1858
restricted { false }
-
1854
gated { false }
-
1
account
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :catalogue_content, class: "BxBlockCatalogue::CatalogueContent" do
-
37
custom_field_name { "MyString" }
-
31
value { "MyString" }
-
1
catalogue
-
1
custom_field
-
37
status { false }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :catalogue, class: 'BxBlockCatalogue::Catalogue' do
-
988
sku { Faker::Alphanumeric.alphanumeric(number: 14, min_numeric: 5) }
-
990
bibc { Faker::Alphanumeric.alpha(number: 8) }
-
990
product_title { Faker::Name.unique.name }
-
940
product_image { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg')) }
-
975
fulfilled_type {'partner'}
-
990
product_type {'standard'}
-
957
content_status {'in_progress'}
-
945
stocks {5}
-
1
category
-
1
brand
-
1
parent_catalogue
-
691
status { false }
-
-
1
after(:build) do |catalogue|
-
989
if catalogue.parent_catalogue.present?
-
989
catalogue.besku = catalogue.parent_catalogue.besku
-
end
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :catalogue_variant ,class: 'BxBlockCatalogue::CatalogueVariant' do
-
40
group_name { Faker::Lorem.word }
-
1
micro_category
-
1
trait :with_account do
-
1
association :seller, factory: :account
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :catalogue_offer, class: 'BxBlockCatalogue::CatalogueOffer' do
-
38
price_info { "9.99" }
-
38
sale_price { "9.99" }
-
37
barcode_id { "" }
-
38
bar_code_info { "MyString" }
-
36
sale_schedule_from { Date.today }
-
30
sale_schedule_to { Date.today }
-
38
warranty { "MyString" }
-
38
comments { "MyString" }
-
30
status { false }
-
1
catalogue
-
1
barcode
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :deal_catalogue, class: 'BxBlockCatalogue::DealCatalogue' do
-
1
deal
-
1
catalogue
-
73
status { 1 }
-
93
deal_price { "9.99" }
-
-
1
trait :with_account do
-
1
association :seller, factory: :account
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :deal, class: 'BxBlockCatalogue::Deal' do
-
139
deal_name { "MyString" }
-
139
deal_code { "MyString" }
-
135
start_date { Date.today }
-
132
end_date { Date.today }
-
129
discount_type {'percentage'}
-
129
discount_value { 0.0 }
-
98
status { true }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :feature_bullet, class: 'BxBlockCatalogue::FeatureBullet' do
-
12
value { "MyString" }
-
1
product_content
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :gated_brand, class: "BxBlockCatalogue::GatedBrand" do
-
10
approved { false }
-
10
reseller_permit_document { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'document.pdf')) }
-
1
brand
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :group_attribute, class: 'BxBlockCatalogue::GroupAttribute' do
-
1
product_variant_group
-
66
attribute_name { "MyString" }
-
66
option { "MyString" }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :helpful_review, class: 'BxBlockCatalogue::HelpfulReview' do
-
1
association :customer, factory: :account
-
1
review
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :image_url, class: 'BxBlockCatalogue::ImageUrl' do
-
40
url { "https://fastly.picsum.photos/id/861/200/300.jpg?hmac=kssNLkcAZTJQKpPCSrGodykV8A6CStZxL7dHvtsVUD0" }
-
1
product_content
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :parent_catalogue ,class: 'BxBlockCatalogue::ParentCatalogue'do
-
989
sku {Faker::Alphanumeric.alpha(number: 5)}
-
989
besku {Faker::Alphanumeric.alpha(number: 10)}
-
988
product_title {Faker::Name.unique.name}
-
989
product_image {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg'))}
-
1
category
-
1
brand
-
989
prod_model_no {Faker::Alphanumeric.alpha(number: 5).upcase}
-
989
details {"string"}
-
988
status { false }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :product_content, class: 'BxBlockCatalogue::ProductContent' do
-
268
gtin { Faker::Number.number(digits: 9) + Faker::Number.number(digits: 3)}
-
# unique_psku { Faker::Alphanumeric.alpha(number: 8) }
-
268
brand_name { "MyString" }
-
166
product_title { "MyString" }
-
268
mrp { 10.00 }
-
268
retail_price { 11.00 }
-
268
long_description { "MyText" }
-
268
whats_in_the_package { "MyString" }
-
268
country_of_origin { "India" }
-
165
product_color {"Grey"}
-
268
dispenser_type { "MyString" }
-
268
scent_type { "MyString" }
-
268
target_use { "MyString" }
-
268
style_name { "MyString" }
-
1
catalogue
-
-
1
after(:build) do |product_content|
-
267
product_content.feature_bullets_attributes = [{ value: "feature 1" }]
-
267
product_content.image_urls_attributes = [{ url: "www.img.com" }]
-
-
267
if product_content.catalogue.present?
-
267
product_content.unique_psku = product_content.catalogue.sku
-
end
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :product_variant_group, class: 'BxBlockCatalogue::ProductVariantGroup' do
-
69
product_sku { Faker::Alphanumeric.alpha(number: 5) }
-
70
product_bibc { Faker::Alphanumeric.alpha(number: 8) }
-
70
product_description {Faker::Lorem.sentence(word_count: 3)}
-
70
price { "500" }
-
70
product_title {Faker::Lorem.word}
-
70
product_images {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg'))}
-
1
catalogue
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :restricted_brand, class: "BxBlockCatalogue::RestrictedBrand" do
-
18
approved { false }
-
18
reseller_permit_document { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'document.pdf')) }
-
1
brand
-
1
trait :with_account do
-
1
association :seller, factory: :account
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :review, class: 'BxBlockCatalogue::Review' do
-
372
title { Faker::Lorem.paragraph }
-
372
description { Faker::Lorem.paragraph(sentence_count: 3) }
-
79
rating { Faker::Number.between(from: 1, to: 5) }
-
77
review_type { 'product' }
-
1
association :account, factory: :account
-
1
association :catalogue, factory: :catalogue
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :shipping_detail, class: 'BxBlockCatalogue::ShippingDetail' do
-
12
shipping_length { "9.99" }
-
12
shipping_length_unit { "Gram" }
-
12
shipping_height { "9.99" }
-
12
shipping_height_unit { "Centimeter" }
-
12
shipping_width { "9.99" }
-
12
shipping_width_unit { "Feet" }
-
12
shipping_weight { "9.99" }
-
12
shipping_weight_unit { "Kilogram" }
-
1
product_content
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :size_and_capacity, class: 'BxBlockCatalogue::SizeAndCapacity' do
-
12
size { 0 }
-
12
size_unit { "Grams" }
-
12
capacity { 0 }
-
12
capacity_unit { "Litre" }
-
12
hs_code { "455678" }
-
12
prod_model_name { "MyString" }
-
12
prod_model_number { "MyS45tring" }
-
12
number_of_pieces { 1 }
-
1
product_content
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :special_feature, class: 'BxBlockCatalogue::SpecialFeature' do
-
9
value { "MyString" }
-
1
product_content
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :variant_attribute ,class: 'BxBlockCatalogue::VariantAttribute' do
-
8
attribute_name { Faker::Lorem.word }
-
1
catalogue_variant
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :warehouse_catalogue, class: 'BxBlockCatalogue::WarehouseCatalogue' do
-
1
association :warehouse, factory: :warehouse
-
1
association :catalogue, factory: :catalogue
-
1
association :product_variant_group, factory: :product_variant_group
-
4
stocks { Faker::Number.number(digits: 3) }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :warehouse, class: 'BxBlockCatalogue::Warehouse' do
-
60
warehouse_type { "MyString" }
-
60
warehouse_name { "MyString" }
-
61
warehouse_address_1 { "MyString" }
-
61
warehouse_address_2 { "MyString" }
-
61
contact_number { 9087654321 }
-
61
contact_person { "MyString" }
-
61
processing_days { 3 }
-
1
account
-
end
-
end
-
1
def uploaded_image(file_name = 'Sample.jpg')
-
3796
Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', file_name))
-
end
-
-
1
FactoryBot.define do
-
1
factory :category ,class: 'BxBlockCategories::Category'do
-
1884
name { Faker::Lorem.characters(number: 10, min_alpha: 4) }
-
1899
category_image { uploaded_image }
-
1899
header_image { uploaded_image }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :custom_field, class: 'BxBlockCategories::CustomField' do
-
23
field_name { "MyString" }
-
126
data_type { "MyString" }
-
125
mandatory { false }
-
1
association :fieldable, factory: :category
-
-
1
after(:build) do |custom_field|
-
125
custom_field.custom_fields_options << FactoryBot.build(:custom_fields_option, custom_field: custom_field)
-
end
-
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :custom_fields_option, class: 'BxBlockCategories::CustomFieldsOption' do
-
126
option_name { "My Option" }
-
1
custom_field
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :micro_category, class: 'BxBlockCategories::MicroCategory' do
-
134
name { Faker::Lorem.characters(number: 9, min_alpha: 5) }
-
1
mini_category
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :mini_category,class: 'BxBlockCategories::MiniCategory' do
-
146
name { Faker::Lorem.characters(number: 11, min_alpha: 5) }
-
1
sub_category
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :sub_category ,class: 'BxBlockCategories::SubCategory'do
-
212
name { Faker::Lorem.characters(number: 11, min_alpha: 6)}
-
1
category
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :admin_reply, class: 'BxBlockContactUs::AdminReply' do
-
15
description { "MyText" }
-
15
image {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg'))}
-
1
association :contact, factory: :contact
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :contact, class: 'BxBlockContactUs::Contact' do
-
26
first_name { 'John' }
-
26
last_name { 'Doe' }
-
26
title { 'general feedback' }
-
26
email { 'john.doe@example.com' }
-
26
description { 'dummy description' }
-
26
contact_type { 'feedback' }
-
26
image {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg'))}
-
end
-
-
end
-
1
FactoryBot.define do
-
1
factory :coupon, class: 'BxBlockCouponCg::CouponCode' do
-
40
title { Faker::Lorem.sentence }
-
40
code { generate(:unique_coupon_code) }
-
40
discount { Faker::Number.between(from: 5, to: 50) }
-
39
valid_from { Faker::Date.backward(days: 10) }
-
39
valid_to { Faker::Date.forward(days: 10) }
-
-
end
-
1
sequence :unique_coupon_code do |n|
-
39
"#{Faker::Number.unique.number(digits: 8)}_#{n}"
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :subscribe_coupon, class: 'BxBlockCouponCg::SubscribeCoupon' do
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :advertisement, class: "BxBlockCustomAds::Advertisement" do
-
15
name { "Advertisement Name" }
-
15
description { "This is a description of the advertisement" }
-
15
duration { 15 }
-
12
status { 1 }
-
15
start_at { Faker::Date.forward(days: 2) }
-
15
expire_at { Faker::Date.between(from: start_at + 1, to: start_at + 30) }
-
15
banner_ad { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg')) }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :author_favorite_book, class: "BxBlockDashboard::AuthorFavoriteBook" do
-
1
title { "MyString" }
-
4
status {true}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :banner_group, class: "BxBlockDashboard::BannerGroup" do
-
85
initialize_with { BxBlockDashboard::BannerGroup.find_or_create_by(group_name: 'header_group_1') }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :banner, class: "BxBlockDashboard::Banner" do
-
80
title {'pixel'}
-
80
description {'latest'}
-
80
button_text {'shop now'}
-
80
button_link {'/product_link'}
-
77
banner_type { 'slideshow' }
-
77
section {'header'}
-
80
banner_image { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg')) }
-
1
banner_group
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :favorite_book_catalogue, class: "BxBlockDashboard::AuthorFavoriteBookCatalogue" do
-
1
catalogue
-
1
author_favorite_book
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :header_category, class: "BxBlockDashboard::HeaderCategory" do
-
6
sequence(:sequence_no) { |n| n % 6 + 1 }
-
1
category
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :most_popular_category, class: "BxBlockDashboard::MostPopularCategory" do
-
6
sequence(:sequence_no) { |n| n % 6 + 1 }
-
1
category
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :top_brand, class: "BxBlockDashboard::TopBrand" do
-
11
sequence(:sequence_no) { |n| n % 6 + 1 }
-
1
brand
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :trending_product_selection, class: "BxBlockDashboard::TrendingProduct" do
-
1
catalogue
-
1
trending_product
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :trending_product, class: "BxBlockDashboard::TrendingProduct" do
-
1
slider { BxBlockDashboard::TrendingProduct.sliders.keys.sample }
-
34
sale_ad_image {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg'))}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :weekly_deal, class: "BxBlockDashboard::WeeklyDeal" do
-
1
weekly_homiee_deal
-
1
caption { "MyString" }
-
1
discount_percent { "9.99" }
-
1
url { "https://" }
-
1
bg_image {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg'))}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :weekly_homiee_deal, class: "BxBlockDashboard::WeeklyHomieeDeal" do
-
19
start_time { Date.tomorrow }
-
19
end_time { Date.tomorrow + 2.days }
-
16
status {false}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :favourite, class: "BxBlockFavourites::Favourite" do
-
8
favouriteable_id { FactoryBot.create(:catalogue).id }
-
16
favouriteable_type { "BxBlockCatalogue::Catalogue" }
-
-
1
trait :with_account do
-
1
association :user, factory: :account
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :invoice_billing, class: "BxBlockInvoicebilling::InvoiceBilling" do
-
-
1
trait :with_account do
-
1
association :customer, factory: :account
-
end
-
-
1
trait :with_shopping_cart_order do
-
1
association :order, factory: :with_shopping_cart_order
-
end
-
-
1
trait :with_shopping_cart_order_item do
-
1
association :order_item, factory: :with_shopping_cart_order_item
-
end
-
-
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :delivery_request, class: 'BxBlockOrderManagement::DeliveryRequest' do
-
1
warehouse
-
14
warehouse_name { 'warehouse 1' }
-
1
trait :with_account do
-
1
association :seller, factory: :account
-
end
-
1
trait :with_shopping_cart_order do
-
1
association :order, factory: :shopping_cart_order
-
end
-
14
address_1 { '123 Main St' }
-
14
address_2 { 'Apt 456' }
-
14
status { 'pending' }
-
-
1
after(:build) do |delivery_request|
-
13
if delivery_request.order.present?
-
13
delivery_request.order_number = delivery_request.order.order_number
-
end
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :order_status, class: 'BxBlockOrderManagement::OrderStatus' do
-
1
sequence(:name) do |n|
-
18
Faker::Lorem.characters(number: 10).gsub(/\d/, '').upcase
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :stock_intake, class: 'BxBlockOrderManagement::StockIntake' do
-
1
catalogue { nil }
-
6
stock_value { "9.99" }
-
6
stock_qty { 1 }
-
6
ship_date { Date.tomorrow }
-
6
receiving_date { Date.tomorrow + 2.days }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :wms_consignment_order, class: "BxBlockOrderManagement::WmsConsignmentOrder" do
-
1
order_number { "MyString" }
-
1
seller
-
1
catalogue
-
1
quantity { 1 }
-
1
unit_price { "9.99" }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :wms_event_update do
-
1
warehouse_code { "MyString" }
-
1
seller_email { "MyString" }
-
1
consignment_type { "MyString" }
-
1
shipment_number { "MyString" }
-
1
po_number { "MyString" }
-
1
old_state { "MyString" }
-
1
new_state { "MyString" }
-
1
event_on { "2024-11-05 12:05:10" }
-
1
time_zone { "MyString" }
-
1
products { "" }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :wms_product_info, class: 'BxBlockOrderManagement::WmsProductInfo' do
-
1
seller
-
1
catalogue
-
1
product_information_id { "1" }
-
1
product_dimensions_info { "sku-wms" }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :product_view, class: "BxBlockSalesreporting::ProductView" do
-
1
catalogue
-
1
user { nil }
-
2
viewed_at { Time.now }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :seo_setting, class: 'BxBlockSeoSetting::SeoSetting' do
-
4
page_name {Faker::Lorem.unique.word}
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :shopping_cart_order_item, class: "BxBlockShoppingCart::OrderItem" do
-
165
price {123}
-
158
quantity {2}
-
166
taxable {false}
-
166
taxable_value {0.0}
-
1
catalogue
-
1
trait :with_shopping_cart_order do
-
1
association :order, factory: :shopping_cart_order
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :shopping_cart_order, class: "BxBlockShoppingCart::Order" do
-
206
status {0}
-
206
total_fees {123}
-
206
total_tax {0.0}
-
206
discount {0.0}
-
206
final_price {123}
-
-
1
trait :with_account do
-
1
association :customer, factory: :account
-
end
-
-
1
trait :with_user_delivery_address do
-
1
association :shipping_address, factory: :user_delivery_address
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :return_exchange_request, class: 'BxBlockShoppingCart::ReturnExchangeRequest' do
-
11
order_number { "0000-0000000001" }
-
11
request_type { "MyString" }
-
11
request_reason { "MyString" }
-
11
description { "MyText" }
-
-
1
trait :with_shopping_cart_order do
-
1
association :order, factory: :shopping_cart_order
-
end
-
1
trait :with_account do
-
1
association :customer, factory: :account
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :return_reason_detail, class: "BxBlockShoppingCart::ReturnReasonDetail" do
-
16
title { "MyString" }
-
16
details { "MyText" }
-
16
reason_type { "return_reason" }
-
# trait :with_shopping_cart_order_item do
-
# association :order_item, factory: :shopping_cart_order_item
-
# end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :shipped_order_detail, class: "BxBlockShoppingCart::ShippedOrderDetail" do
-
7
shipping_details { "MyText" }
-
7
courier_name { "courier name" }
-
7
tracking_number {"tracking313234number"}
-
1
trait :with_shopping_cart_order do
-
1
association :order, factory: :shopping_cart_order
-
end
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :store_dashboard_section, class: "BxBlockStoreManagement::StoreDashboardSection" do
-
1
section_name { "section_1" }
-
1
section_type { "3_grids_layout" }
-
3
banner_name { "" }
-
4
banner_image { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg')) }
-
4
banner_url {"www.example.com"}
-
1
store
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :store_menu, class: "BxBlockStoreManagement::StoreMenu" do
-
5
title { "MyString" }
-
# store_name { "MyString" }
-
7
banner_name { "MyString" }
-
7
position {Faker::Number.between(from: 1, to: 8)}
-
1
store
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :store_section_grid, class: "BxBlockStoreManagement::StoreSectionGrid" do
-
1
grid_name { Faker::Name.unique.name }
-
3
grid_url { "www.example.com" }
-
1
grid_no { "grid_1" }
-
3
grid_image { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'Sample.jpg')) }
-
1
store_dashboard_section
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :store, class: "BxBlockStoreManagement::Store" do
-
23
store_name { Faker::Name.unique.name + Faker::Lorem.word }
-
23
store_year { 1 }
-
23
store_url { "MyString" }
-
23
website_social_url { "MyString" }
-
23
brand_trade_certificate {Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures','files', 'document.pdf'))}
-
20
approve { true }
-
1
brand
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :social_platform, class: 'BxBlockSupport::SocialPlatform' do
-
4
social_media { "MyString" }
-
4
social_media_url { "MyString" }
-
5
social_icon { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'files', 'Sample.jpg')) }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :static_page, class: 'BxBlockSupport::StaticPage' do
-
7
title { Faker::Lorem.word + rand(1..10000).to_s }
-
11
content { "MyText" }
-
11
status { true }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :support_document, class: 'BxBlockSupport::SupportDocument' do
-
12
page_title { Faker::Lorem.word + rand(1..10000).to_s}
-
12
content { Faker::Lorem.word }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :support, class: 'BxBlockSupport::Support' do
-
7
first_name { "MyString" }
-
7
last_name { "MyString" }
-
7
email { Faker::Internet.email }
-
7
details { "MyText" }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :privacy_and_legal_policy, class: 'BxBlockTermsandconditions::PrivacyAndLegalPolicy' do
-
7
title { Faker::Lorem.word + rand(1..10000).to_s }
-
7
content { "privacy content body" }
-
7
status { true }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :seller_static_page, class: 'BxBlockTermsandconditions::SellerStaticPage' do
-
18
title { Faker::Lorem.word + rand(1..10000).to_s}
-
22
content { Faker::Lorem.word }
-
14
section { 'header' }
-
20
status { false }
-
end
-
end
-
1
FactoryBot.define do
-
1
factory :terms_policy ,class: 'BxBlockTermsandconditions::TermsPolicy'do
-
7
page_title { Faker::Lorem.word + rand(1..10000).to_s}
-
7
content { Faker::Lorem.word }
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::ExpireOffersAndDealsJob, type: :job do
-
1
describe '#perform' do
-
4
let!(:account) { FactoryBot.create(:account, user_type: 'seller') }
-
4
let!(:catalogue) { FactoryBot.create(:catalogue, seller: account) }
-
4
let!(:product_content) { FactoryBot.create(:product_content, catalogue: catalogue) }
-
4
let!(:active_offer) { FactoryBot.create(:catalogue_offer, sale_schedule_to: Time.current + 1.day, status: true) }
-
4
let!(:expired_offer) { FactoryBot.create(:catalogue_offer, sale_schedule_to: Time.current - 1.day, status: true) }
-
-
4
let!(:active_deal) { FactoryBot.create(:deal, end_date: Time.current + 1.day, status: true) }
-
1
let!(:expired_deal) do
-
3
deal = FactoryBot.build(:deal, start_date: Time.current - 10.days, end_date: Time.current - 1.day, status: true)
-
3
deal.save(validate: false)
-
3
deal
-
end
-
-
4
let!(:deal_catalogue) { FactoryBot.create(:deal_catalogue, deal: expired_deal, status: 'approved', seller: account) }
-
-
1
it 'expires catalogue offers whose sale_schedule_to has passed' do
-
1
described_class.perform_now
-
1
expect(active_offer.reload.status).to eq(true)
-
1
expect(expired_offer.reload.status).to eq(false)
-
end
-
-
1
it 'expires deals whose end_date has passed' do
-
1
described_class.perform_now
-
1
expect(active_deal.reload.status).to eq(true)
-
1
expect(expired_deal.reload.status).to eq(false)
-
end
-
-
1
it 'updates the status of associated deal catalogues to expired' do
-
2
expect { described_class.perform_now }
-
2
.to change { deal_catalogue.reload.status }.from('approved').to('expired')
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockContactUs::AdminReplyMailer, type: :mailer do
-
4
let(:admin_reply) { create(:admin_reply) }
-
-
1
describe 'notification' do
-
2
let(:mail) { BxBlockContactUs::AdminReplyMailer.notification(admin_reply) }
-
-
1
it 'renders the headers' do
-
1
expect(mail.subject.strip).to eq('Admin Reply Notification')
-
end
-
1
it 'does not include attachments when image is not attached' do
-
1
admin_reply.image.detach
-
1
mail_without_image = BxBlockContactUs::AdminReplyMailer.notification(admin_reply)
-
1
user_added_attachments = mail_without_image.attachments.reject do |attachment|
-
1
attachment.content_id.nil? || attachment.content_id.start_with?('<')
-
end
-
1
expect(user_added_attachments).to be_empty
-
end
-
1
it 'does not include attachments when both image and contact image are not attached' do
-
1
admin_reply.image.detach
-
1
admin_reply.contact.image.detach
-
1
mail_without_images = BxBlockContactUs::AdminReplyMailer.notification(admin_reply)
-
1
user_added_attachments = mail_without_images.attachments.reject do |attachment|
-
attachment.content_id.nil? || attachment.content_id.start_with?('<')
-
end
-
1
expect(user_added_attachments).to be_empty
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::Account, type: :model do
-
1
describe 'should have has_one association' do
-
2
it { should have_one(:blacklist_user).class_name('AccountBlock::BlackListUser').dependent(:destroy) }
-
end
-
-
1
describe 'should have has_many association' do
-
2
it { should have_many(:stores).class_name('BxBlockStoreManagement::Store').dependent(:destroy) }
-
2
it { should have_many(:seller_documents).class_name('AccountBlock::SellerDocument').dependent(:destroy) }
-
2
it { should have_many(:user_delivery_addresses).class_name('AccountBlock::UserDeliveryAddress').dependent(:destroy) }
-
2
it { should have_many(:seller_documents).class_name('AccountBlock::SellerDocument').dependent(:destroy) }
-
2
it { should have_many(:user_delivery_addresses).class_name('AccountBlock::UserDeliveryAddress').dependent(:destroy) }
-
2
it { should have_many(:brands).class_name('BxBlockCatalogue::Brand').dependent(:destroy) }
-
2
it { should have_many(:favourites).class_name('BxBlockFavourites::Favourite').with_foreign_key('user_id').dependent(:destroy) }
-
2
it { should have_many(:orders).class_name('BxBlockShoppingCart::Order').with_foreign_key('customer_id').dependent(:destroy) }
-
2
it { should have_many(:subscribe_coupons).class_name('BxBlockCouponCg::SubscribeCoupon').dependent(:destroy) }
-
2
it { should have_many(:coupon_codes).through(:subscribe_coupons).class_name('BxBlockCouponCg::CouponCode') }
-
2
it { should have_many(:review_and_ratings).class_name('BxBlockCatalogue::Review').dependent(:destroy) }
-
end
-
-
1
describe 'enum' do
-
2
it { should define_enum_for(:status).with_values(%i[regular suspended deleted]) }
-
end
-
-
1
describe 'scopes' do
-
2
let!(:buyer_account) { create(:account, user_type: 'buyer') }
-
2
let!(:seller_account) { create(:account, user_type: 'seller') }
-
-
1
describe '.buyer_accounts' do
-
1
it 'returns accounts with user_type "buyer"' do
-
1
expect(AccountBlock::Account.buyer_accounts).to include(buyer_account)
-
1
expect(AccountBlock::Account.buyer_accounts).not_to include(seller_account)
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe AccountBlock::SellerDocument, type: :model do
-
-
4
let(:document) { [fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "document.pdf"))] }
-
-
1
describe "associations" do
-
2
it { should belong_to(:account).class_name("AccountBlock::Account") }
-
2
it { should have_many_attached(:document_files) }
-
end
-
-
1
describe "custom validations" do
-
1
context "when document type is vat_certificate and document_files are not attached" do
-
3
let(:seller_document) { build(:seller_document, document_type: "VAT Certificate or Reason for not having it") }
-
-
1
it "should validate presence of vat_reason" do
-
1
expect(seller_document).to validate_presence_of(:vat_reason)
-
end
-
-
1
it "should set vat_reason to nil before update if vat_document_present?" do
-
1
seller_document.save
-
-
1
expect {
-
1
seller_document.update(document_files: document)
-
2
}.to change { seller_document.vat_reason }.to(nil)
-
end
-
end
-
-
1
context "when document type is iban_certificate and document_files are attached" do
-
3
let(:seller_document) { build(:seller_document, document_type: "IBAN Certificate or Bank Details", document_files: document) }
-
-
1
it "should not validate presence of account_no, iban, bank_address, name, bank_name, and swift_code" do
-
1
expect(seller_document).not_to validate_presence_of(:account_no)
-
1
expect(seller_document).not_to validate_presence_of(:iban)
-
1
expect(seller_document).not_to validate_presence_of(:bank_address)
-
1
expect(seller_document).not_to validate_presence_of(:name)
-
1
expect(seller_document).not_to validate_presence_of(:bank_name)
-
1
expect(seller_document).not_to validate_presence_of(:swift_code)
-
end
-
-
1
it "should set account_no, iban, bank_address, name, bank_name, and swift_code to nil before update if iban_document_present?" do
-
1
seller_document.save
-
1
expect {
-
1
seller_document.update(document_files: document)
-
2
}.to change { [seller_document.account_no, seller_document.iban, seller_document.bank_address, seller_document.name, seller_document.bank_name, seller_document.swift_code] }.to([nil, nil, nil, nil, nil, nil])
-
end
-
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::Catalogue, type: :model do
-
1
describe 'should have has_one association' do
-
2
it { should have_one(:barcode).class_name('BxBlockCatalogue::Barcode').dependent(:destroy) }
-
end
-
-
1
describe 'should have has_many association' do
-
2
it { should have_many(:coupon_codes).through(:subscribe_coupons).class_name('BxBlockCouponCg::CouponCode') }
-
2
it { should have_many(:subscribe_coupons).class_name('BxBlockCouponCg::SubscribeCoupon').dependent(:destroy) }
-
2
it { should have_many(:review_and_ratings).class_name('BxBlockCatalogue::Review').dependent(:destroy) }
-
end
-
-
1
describe 'callbacks' do
-
6
let(:category) { create(:category) }
-
6
let(:sub_category) { create(:sub_category, category: category) }
-
6
let(:mini_category) { create(:mini_category, sub_category: sub_category) }
-
6
let(:micro_category) { create(:micro_category, mini_category: mini_category) }
-
6
let(:custom_field_1) { create(:custom_field, field_name: 'Custom Field 1', fieldable: category) }
-
6
let(:custom_field_2) { create(:custom_field, field_name: 'Custom Field 2', fieldable: sub_category) }
-
6
let(:custom_field_3) { create(:custom_field, field_name: 'Custom Field 3', fieldable: mini_category) }
-
6
let(:custom_field_4) { create(:custom_field, field_name: 'Custom Field 4', fieldable: micro_category) }
-
5
let(:catalogue) { create(:catalogue, category: category, sub_category: sub_category, mini_category: mini_category, micro_category: micro_category, content_status: 'approved', status: true) }
-
2
let(:field_name) {"Updated Field Name"}
-
-
1
before do
-
5
[custom_field_1, custom_field_2, custom_field_3, custom_field_4]
-
end
-
-
1
it 'creates catalogue contents for associated custom fields' do
-
-
-
1
expect(catalogue.catalogue_contents.pluck(:custom_field_id)).to contain_exactly(custom_field_1.id, custom_field_2.id, custom_field_3.id, custom_field_4.id)
-
1
expect(catalogue.catalogue_contents.pluck(:custom_field_name)).to contain_exactly(custom_field_1.field_name, custom_field_2.field_name, custom_field_3.field_name, custom_field_4.field_name)
-
end
-
-
1
it 'updates custom_field_name if it has changed' do
-
1
custom_field_2.update(field_name: field_name)
-
-
1
expect {
-
catalogue.update_attributes(sku: '123SKU456')
-
}
-
1
expect(catalogue.catalogue_contents.find_by(custom_field_id: custom_field_2.id).custom_field_name).to eq(field_name)
-
-
end
-
-
1
it 'updates archived status' do
-
1
catalogue.content_status = 'archived'
-
1
catalogue.save
-
1
expect(catalogue.status).to eq(false)
-
end
-
-
2
it { should validate_presence_of(:sku) }
-
-
1
it 'validates sku format' do
-
1
valid_sku = "ABC#123-_.{}[]()/"
-
1
invalid_sku = "ABCDw"
-
-
1
catalogue.sku = valid_sku
-
1
expect(catalogue).to be_valid
-
-
1
catalogue.sku = invalid_sku
-
1
expect(catalogue).to_not be_valid
-
1
expect(catalogue.errors[:sku]).to include("should be alphanumeric and special characters")
-
end
-
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::Deal, type: :model do
-
-
1
it "is valid when end date is after start date" do
-
1
deal = build(:deal, start_date: Date.today, end_date: Date.tomorrow,status: true)
-
1
expect(deal).to be_valid
-
end
-
-
1
it "is invalid when end date is before start date" do
-
1
deal = build(:deal, start_date: Date.tomorrow, end_date: Date.today,status: true)
-
1
expect(deal).to be_invalid
-
1
expect(deal.errors[:end_date]).to include("must be after the start date")
-
end
-
-
1
it "validates presence and length of deal_name and deal_code" do
-
1
deal = build(:deal,
-
deal_name: "dealnameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
-
deal_code: "dealcodeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
-
)
-
1
expect(deal).to be_invalid
-
1
expect(deal.errors[:deal_name]).to include("is too long (maximum is 50 characters)")
-
1
expect(deal.errors[:deal_code]).to include("is too long (maximum is 50 characters)")
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::ProductVariantGroup, type: :model do
-
4
let(:catalogue) { create(:catalogue) }
-
4
let(:product_content) { create(:product_content, catalogue: catalogue) }
-
4
let!(:size_and_capacity) { create(:size_and_capacity, product_content: product_content) }
-
4
let!(:shipping_detail) { create(:shipping_detail, product_content: product_content) }
-
4
let!(:image_urls) { create(:image_url, product_content: product_content) }
-
4
let!(:feature_bullets) { create(:feature_bullet, product_content: product_content) }
-
4
let(:product_variant_group) { build(:product_variant_group, catalogue: catalogue) }
-
-
1
describe 'validations' do
-
1
it 'validates presence of product_sku' do
-
1
product_variant_group.product_sku = nil
-
1
expect(product_variant_group).not_to be_valid
-
1
expect(product_variant_group.errors[:product_sku]).to include("can't be blank")
-
end
-
-
1
it 'validates uniqueness of product_sku' do
-
1
create(:product_variant_group, product_sku: 'unique_sku')
-
1
product_variant_group.product_sku = 'unique_sku'
-
1
expect(product_variant_group).not_to be_valid
-
1
expect(product_variant_group.errors[:product_sku]).to include('must be unique across catalogues and product variant groups')
-
end
-
end
-
-
1
describe '#create_and_associate_variant_product' do
-
1
it 'creates a variant product associated with the product_variant_group' do
-
1
product_variant_group.save!
-
1
product_variant_group.create_and_associate_variant_product
-
1
product_variant_group.reload
-
1
expect(product_variant_group.variant_product).not_to be_nil
-
1
expect(product_variant_group.variant_product.parent_product).to eq(catalogue)
-
1
expect(product_variant_group.variant_product.is_variant).to be true
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::Review, type: :model do
-
-
1
describe 'associations' do
-
2
it { should belong_to(:catalogue).class_name('BxBlockCatalogue::Catalogue')}
-
2
it { should belong_to(:account).with_foreign_key('reviewer_id').class_name('AccountBlock::Account')}
-
end
-
-
1
describe 'validation' do
-
2
it { should validate_presence_of(:reviewer_id) }
-
2
it { should validate_presence_of(:catalogue_id) }
-
2
it { should validate_presence_of(:rating) }
-
end
-
-
1
describe 'scopes' do
-
3
let!(:approved_review) { create(:review, is_approved: true) }
-
3
let!(:seller_review) { create(:review, review_type: 'seller') }
-
-
1
describe '.approved_reviews' do
-
1
it 'returns approved reviews' do
-
1
expect(BxBlockCatalogue::Review.approved_reviews).to include(approved_review)
-
end
-
end
-
-
1
describe '.seller_reviews' do
-
1
it 'returns seller reviews' do
-
1
expect(BxBlockCatalogue::Review.seller_reviews).to include(seller_review)
-
end
-
end
-
end
-
-
1
describe 'validations' do
-
1
it 'validates that rating is greater than or equal to 1' do
-
1
should validate_numericality_of(:rating).is_greater_than_or_equal_to(1)
-
end
-
-
1
it 'validates that rating is less than or equal to 5' do
-
1
should validate_numericality_of(:rating).is_less_than_or_equal_to(5)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCatalogue::Warehouse, type: :model do
-
3
subject(:warehouse) { FactoryBot.build(:warehouse) }
-
# it { is_expected.to validate_presence_of(:warehouse_type) }
-
2
it { is_expected.to validate_presence_of(:warehouse_name) }
-
# it { is_expected.to validate_presence_of(:warehouse_address) }
-
-
1
describe 'should have has_many association' do
-
# it { should have_many(:catalogues).class_name('BxBlockCatalogue::Catalogue') }
-
2
it { should belong_to(:account).class_name('AccountBlock::Account').optional(true) }
-
-
end
-
end
-
# frozen_string_literal: true
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCategories::CustomField, type: :model do
-
1
describe '#update_catalogue_contents_custom_field_name' do
-
3
let(:category) {create(:category)}
-
3
let!(:custom_field) { create(:custom_field, field_name: 'Old Field Name',fieldable: category) }
-
2
let(:catalogue) {create(:catalogue, category: category)}
-
2
let(:field_name) {"New Field Name"}
-
-
1
it 'updates the custom_field_name for associated catalogue_contents' do
-
1
custom_field.update(field_name: field_name)
-
-
1
expect(catalogue.catalogue_contents.first.custom_field_name).to eq(field_name)
-
end
-
-
1
it 'updates the custom_field_name for associated catalogue_contents' do
-
1
custom_field_new = create(:custom_field, field_name: 'custom',fieldable: category)
-
1
catalogue_1 = create(:catalogue, category: category)
-
1
custom_field_new.catalogue_contents << catalogue_1.catalogue_contents
-
-
4
expect { custom_field_new.update(field_name: "update field") }.to change { catalogue_1.catalogue_contents.first.custom_field_name }
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockContactUs::AdminReply, type: :model do
-
1
describe 'associations' do
-
2
it { should belong_to(:contact).class_name('BxBlockContactUs::Contact') }
-
2
it { should have_one_attached(:image) }
-
end
-
-
1
describe 'validations' do
-
2
it { should validate_presence_of(:description) }
-
end
-
end
-
# frozen_string_literal: true
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockContactUs::Contact, type: :model do
-
# describe 'should have has_many association' do
-
# it { should have_many(:admin_replies).class_name('BxBlockContactUs::AdminReply').dependent(:destroy) }
-
# end
-
-
1
describe 'nested attributes' do
-
1
it do
-
1
should accept_nested_attributes_for(:admin_replies).
-
allow_destroy(true)
-
end
-
end
-
-
1
describe 'validation' do
-
2
it { should validate_presence_of(:description) }
-
2
it { should validate_presence_of(:email) }
-
2
it { should validate_presence_of(:contact_type) }
-
end
-
-
1
describe 'has_one_attached' do
-
2
it { should have_one_attached(:image) }
-
end
-
-
1
describe 'enum' do
-
1
it do
-
1
should define_enum_for(:contact_type).
-
with_values(
-
complaint: "complaint",
-
feedback: "feedback",
-
query: "query"
-
).
-
backed_by_column_of_type(:string)
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCouponCg::CouponCode, type: :model do
-
1
describe 'validations' do
-
2
it { should validate_presence_of(:title) }
-
2
it { should validate_length_of(:title).is_at_most(50) }
-
2
it { should validate_uniqueness_of(:title).case_insensitive }
-
-
2
it { should validate_presence_of(:code) }
-
2
it { should validate_length_of(:code).is_at_most(50) }
-
2
it { should validate_uniqueness_of(:code).case_insensitive }
-
-
2
it { should validate_presence_of(:discount) }
-
2
it { should validate_numericality_of(:discount).only_integer.is_greater_than_or_equal_to(0) }
-
-
2
it { should validate_presence_of(:valid_from) }
-
2
it { should validate_presence_of(:valid_to) }
-
-
1
it 'validates that end date is after the start date' do
-
1
coupon = build(:coupon, valid_from: Date.today, valid_to: Date.yesterday)
-
1
coupon.valid?
-
1
expect(coupon.errors[:valid_to]).to include('end date must be after the start date')
-
end
-
end
-
-
1
describe 'should have has_many association' do
-
2
it { should have_many(:accounts).through(:subscribe_coupons).class_name('AccountBlock::Account') }
-
2
it { should have_many(:subscribe_coupons).class_name('BxBlockCouponCg::SubscribeCoupon').dependent(:destroy) }
-
end
-
-
# describe 'should have belongs_to association' do
-
# it { should belong_to(:account).class_name('AccountBlock::Account').optional }
-
# end
-
end
-
# spec/models/bx_block_coupon_cg/subscribe_coupon_spec.rb
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockCouponCg::SubscribeCoupon, type: :model do
-
1
describe 'associations' do
-
2
it { should belong_to(:account).class_name('AccountBlock::Account') }
-
2
it { should belong_to(:coupon).class_name('BxBlockCouponCg::CouponCode').with_foreign_key('coupon_code_id') }
-
end
-
end
-
# spec/models/bx_block_order_management/order_status_spec.rb
-
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockOrderManagement::OrderStatus, type: :model do
-
1
describe 'associations' do
-
2
it { is_expected.to have_many(:orders) }
-
2
it { is_expected.to have_many(:order_items) }
-
end
-
-
# describe 'validations' do
-
# it { is_expected.to validate_uniqueness_of(:name) }
-
# end
-
-
1
describe 'scopes' do
-
1
describe '.new_statuses' do
-
1
it 'returns order statuses excluding certain predefined statuses' do
-
1
excluded_statuses = %i[in_cart created placed confirmed in_transit delivered cancelled refunded payment_failed returned payment_pending]
-
1
expect(described_class.new_statuses.pluck(:status)).not_to include(*excluded_statuses)
-
end
-
end
-
end
-
-
1
describe 'constants' do
-
1
it 'defines USER_STATUSES constant' do
-
1
expect(described_class::USER_STATUSES).to eq(%w[in_cart created placed payment_failed payment_pending])
-
end
-
-
1
it 'defines CUSTOM_STATUSES constant' do
-
1
expect(described_class::CUSTOM_STATUSES).to eq(%w[in_cart created placed confirmed in_transit delivered cancelled refunded payment_failed returned payment_pending])
-
end
-
end
-
-
1
describe 'callbacks' do
-
1
describe 'before_save :add_status' do
-
1
it 'does not override status and event_name if they are already present' do
-
1
order_status = described_class.new(name: Faker::Lorem.characters(number: 10).gsub(/\d/, '').upcase, status: 'custom_status', event_name: 'custom_event')
-
1
order_status.save!
-
1
expect(order_status.status).to eq('custom_status')
-
1
expect(order_status.event_name).to eq('custom_event')
-
end
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockSeoSetting::SeoSetting, type: :model do
-
1
describe 'validations' do
-
3
subject { FactoryBot.build(:seo_setting) }
-
-
2
it { should validate_presence_of(:page_name) }
-
2
it { should validate_uniqueness_of(:page_name) }
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::OrderItem, type: :model do
-
1
describe '#calculate_final_price' do
-
1
let(:catalogue) { create(:catalogue) }
-
1
let(:product_content) { create(:product_content, catalogue: catalogue, retail_price: 100.0) }
-
1
let(:order_item) { create(:shopping_cart_order_item, catalogue: catalogue, quantity: 2) }
-
2
let(:customer) { create(:account, user_type: 'buyer') }
-
2
let(:order) { create(:shopping_cart_order, customer: customer) }
-
-
1
before do
-
1
allow(subject).to receive(:order).and_return(order)
-
end
-
-
1
context 'when total discount is 0' do
-
1
it 'calculates final price without discount' do
-
1
allow(subject).to receive(:calculate_total_discount).and_return(0.0)
-
1
allow(subject).to receive(:calculate_total_price).and_return(100.0)
-
1
allow(subject).to receive(:calculate_total_tax).and_return(10.0)
-
-
1
result = subject.calculate_final_price
-
-
1
expect(result).to eq(110.0)
-
end
-
end
-
end
-
-
1
describe '#calculate_final_discount_price' do
-
1
it 'calculates final discount price based on order items' do
-
1
order_item1 = instance_double(BxBlockShoppingCart::OrderItem, discount_price: 10.0, price: 20.0, quantity: 2)
-
1
order_item2 = instance_double(BxBlockShoppingCart::OrderItem, discount_price: 0.0, price: 15.0, quantity: 3)
-
-
1
allow(subject).to receive(:order).and_return(
-
instance_double(BxBlockShoppingCart::Order, order_items: [order_item1, order_item2])
-
)
-
-
1
result = subject.calculate_final_discount_price
-
-
1
expect(result).to eq(65.0)
-
end
-
end
-
-
1
describe '#update_stock_if_catalogue_return' do
-
3
let(:customer) { create(:account, user_type: 'buyer') }
-
3
let(:order) { create(:shopping_cart_order, customer: customer) }
-
3
let(:catalogue) { create(:catalogue, stocks: 10) }
-
3
let!(:warehouse_catalogue) { create(:warehouse_catalogue, catalogue: catalogue, stocks: 5) }
-
-
1
context 'when order status is qc_passed' do
-
2
let(:order_status) { create(:order_status, status: 'qc_passed') }
-
-
1
it 'increments stock in catalogue and warehouse' do
-
1
order_item = create(:shopping_cart_order_item,
-
catalogue: catalogue,
-
quantity: 3,
-
order: order,
-
order_status: order_status)
-
-
1
expect {
-
1
order_item.update(quantity: 3) # triggers after_update callback
-
2
}.to change { catalogue.reload.stocks }.by(3)
-
2
.and change { warehouse_catalogue.reload.stocks }.by(3)
-
end
-
end
-
-
1
context 'when order status is rejected' do
-
2
let(:order_status) { create(:order_status, status: 'rejected') }
-
-
1
it 'increments stock in catalogue and warehouse' do
-
1
order_item = create(:shopping_cart_order_item,
-
catalogue: catalogue,
-
quantity: 2,
-
order: order,
-
order_status: order_status)
-
-
1
expect {
-
1
order_item.update(quantity: 2)
-
2
}.to change { catalogue.reload.stocks }.by(2)
-
2
.and change { warehouse_catalogue.reload.stocks }.by(2)
-
end
-
end
-
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockShoppingCart::Order, type: :model do
-
13
let(:customer) { FactoryBot.create(:account) }
-
11
let(:order_status) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Scheduled') }
-
6
let(:status_ordered) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'Ordered') }
-
5
let(:status_ongoing) { BxBlockOrderManagement::OrderStatus.find_or_create_by(name: 'On Going') }
-
7
let(:order) { described_class.new(customer: customer, order_status: order_status) }
-
3
let(:order2) { FactoryBot.create(:shopping_cart_order, customer: customer, order_status: order_status) }
-
5
let(:seller) { FactoryBot.create(:account, user_type: "seller") }
-
5
let(:catalogue) { FactoryBot.create(:catalogue, seller: seller) }
-
5
let(:warehouse) { FactoryBot.create(:warehouse, account: seller) }
-
5
let(:warehouse_catalogue) { FactoryBot.create(:warehouse_catalogue, warehouse: warehouse, catalogue: catalogue, stocks: 10) }
-
3
let(:order_item) { FactoryBot.create(:shopping_cart_order_item, order: order2, catalogue: catalogue, quantity: 5) }
-
-
1
describe '#assign_default_order_status' do
-
1
it 'assigns default order status before creation' do
-
1
order.save
-
1
expect(order.order_status.name).to eq('Scheduled')
-
end
-
end
-
-
1
describe '#check_order_status' do
-
-
1
it 'allows updating order status if it was not completed' do
-
1
order.order_status = status_ongoing
-
-
1
expect(order).to be_valid
-
end
-
end
-
-
1
describe '#set_current_order' do
-
1
it 'sets the current order for the customer after creation' do
-
1
expect(customer.current_order).to be_nil
-
-
1
order.save
-
-
1
expect(customer.current_order).to eq(order.id)
-
end
-
end
-
-
1
describe '#update_current_order' do
-
1
it 'clears the current order for the customer when order is placed' do
-
1
order.save
-
1
expect(customer.current_order).to eq(order.id)
-
-
1
order.update(order_status: status_ordered)
-
-
1
expect(customer.reload.current_order).to be_nil
-
end
-
-
1
it 'does not clear the current order for the customer if order is not completed' do
-
1
order.save
-
1
expect(customer.current_order).to eq(order.id)
-
-
1
order.update(order_status: status_ongoing)
-
-
1
expect(customer.reload.current_order).to eq(order.id)
-
end
-
end
-
-
1
describe '#add_order_number' do
-
1
it 'adds an order number before creation' do
-
1
expect(order.order_number).to be_nil
-
-
1
order.save
-
-
1
expect(order.order_number).not_to be_nil
-
end
-
end
-
-
1
describe '.next_order_number' do
-
1
it 'generates the next order number' do
-
1
FactoryBot.create(:shopping_cart_order, order_number: '0000-0000000000', customer: customer)
-
-
1
last_order_number = described_class.last.order_number
-
1
expected_next_order_number = last_order_number.succ
-
-
1
expect(described_class.next_order_number).to eq(expected_next_order_number)
-
end
-
end
-
-
1
describe 'assign_shipping_address' do
-
1
it 'updates address_id with user_delivery_address id' do
-
1
user_delivery_address = FactoryBot.create(:user_delivery_address,account: customer,is_default: true)
-
1
order = FactoryBot.create(:shopping_cart_order, customer: customer)
-
-
1
expect(order.customer).to eq(customer)
-
1
expect(order.address_id).to eq(user_delivery_address.id)
-
end
-
end
-
-
1
describe '#update_stocks' do
-
1
before do
-
2
order2.order_items << order_item
-
2
catalogue.warehouse_catalogues << warehouse_catalogue
-
2
order2.reload
-
2
catalogue.reload
-
end
-
1
context 'when the stock is sufficient' do
-
1
it 'decrements the stock by the order item quantity' do
-
1
order2.update(order_status: status_ongoing)
-
1
order2.update(order_status: status_ordered)
-
1
expect(catalogue.reload.stocks).to eq(5)
-
end
-
end
-
-
1
context 'when the stock is not sufficient' do
-
2
let(:order3) { FactoryBot.create(:shopping_cart_order, customer: customer, order_status: order_status) }
-
2
let(:order_item2) { FactoryBot.create(:shopping_cart_order_item, order: order3, catalogue: catalogue, quantity: 10) }
-
-
1
it 'sets the stock to zero' do
-
1
order3.order_items << order_item2
-
1
order3.reload
-
1
warehouse_catalogue.update(stocks: 10)
-
1
catalogue.reload
-
1
order3.update(order_status: status_ongoing)
-
1
order3.update(order_status: status_ordered)
-
1
expect(catalogue.reload.stocks).to eq(0)
-
end
-
end
-
end
-
-
1
describe '#check_warehouse_catalogue_stocks' do
-
3
let(:order4) { FactoryBot.create(:shopping_cart_order, customer: customer, order_status: order_status) }
-
3
let(:order_item3) { FactoryBot.create(:shopping_cart_order_item, order: order4, catalogue: catalogue, quantity: 5) }
-
-
1
before do
-
2
order4.order_items << order_item3
-
2
catalogue.warehouse_catalogues << warehouse_catalogue
-
2
order4.reload
-
2
catalogue.reload
-
end
-
-
1
context 'when the stock is sufficient' do
-
1
it 'allows the order status to be updated to ordered' do
-
1
warehouse_catalogue.update(stocks: 10)
-
1
order4.update(order_status: status_ordered)
-
1
expect(order4.errors[:order_items]).to be_empty
-
end
-
end
-
-
1
context 'when the stock is not sufficient' do
-
1
it 'adds an error to the order' do
-
1
warehouse_catalogue.update(stocks: 2)
-
1
order4.update(order_status: status_ordered)
-
1
catalogue.reload
-
1
out_of_stock_details = [{ id: catalogue.id, product_title: catalogue.product_title }]
-
1
expect(order4.errors[:order_items]).to include(hash_including(:out_of_stock => out_of_stock_details))
-
end
-
end
-
end
-
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockStoreManagement::StoreMenu, type: :model do
-
5
let(:store) { create(:store) }
-
-
1
context 'validations' do
-
1
it 'validates presence of title when store_name is not present' do
-
1
menu = build(:store_menu, store: store, title: nil, store_name: nil)
-
1
expect(menu).not_to be_valid
-
1
expect(menu.errors[:title]).to include("can't be blank")
-
end
-
-
1
it 'validates cover_image presence when store_name is present' do
-
1
menu = build(:store_menu, store: store, store_name: 'Sample Store Name')
-
1
expect(menu).not_to be_valid
-
1
expect(menu.errors[:cover_image]).to include("must be attached when store name is present")
-
1
expect(menu.errors[:logo]).to include("must be attached when store name is present")
-
end
-
-
1
it 'is valid when title is present and store_name is not present' do
-
1
menu = build(:store_menu, store: store, title: 'Sample Title')
-
1
expect(menu).to be_valid
-
end
-
-
1
it 'is valid when cover_image and logo are attached and store_name is present' do
-
1
menu = build(:store_menu, store: store, store_name: 'Sample Store Name', cover_image: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg")), logo: fixture_file_upload(Rails.root.join("spec", "fixtures", "files", "Sample.jpg")))
-
1
expect(menu).to be_valid
-
end
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockStoreManagement::Store, type: :model do
-
1
describe 'attachment' do
-
2
it { should have_one_attached(:brand_trade_certificate) }
-
end
-
-
1
describe 'validations' do
-
2
it { should validate_presence_of(:store_year) }
-
2
it { should validate_presence_of(:store_url) }
-
2
it { should validate_presence_of(:website_social_url) }
-
end
-
-
1
describe 'associations' do
-
2
it { should belong_to(:account).class_name('AccountBlock::Account').optional }
-
2
it { should belong_to(:brand).class_name('BxBlockCatalogue::Brand') }
-
2
it { should have_many(:store_menus).class_name('BxBlockStoreManagement::StoreMenu').dependent(:destroy) }
-
end
-
end
-
1
require 'rails_helper'
-
-
1
RSpec.describe BxBlockTermsandconditions::PrivacyAndLegalPolicy, type: :model do
-
1
describe 'validations' do
-
2
it { should validate_presence_of(:title) }
-
2
it { should validate_presence_of(:content) }
-
end
-
end
-
# This file is copied to spec/ when you run 'rails generate rspec:install'
-
1
require 'spec_helper'
-
1
require 'ostruct'
-
-
1
ENV['RAILS_ENV'] ||= 'test'
-
1
require_relative '../config/environment'
-
# Prevent database truncation if the environment is production
-
1
abort("The Rails environment is running in production mode!") if Rails.env.production?
-
1
require 'rspec/rails'
-
# Add additional requires below this line. Rails is not loaded until this point!
-
1
require 'webmock/rspec'
-
1
require 'mock_redis'
-
1
require 'sidekiq/testing'
-
1
Sidekiq::Testing.fake!
-
-
1
WebMock.disable_net_connect!(allow_localhost: true)
-
-
# Requires supporting ruby files with custom matchers and macros, etc, in
-
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
-
# run as spec files by default. This means that files in spec/support that end
-
# in _spec.rb will both be required and run as specs, causing the specs to be
-
# run twice. It is recommended that you do not name files matching this glob to
-
# end with _spec.rb. You can configure this pattern with the --pattern
-
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
-
#
-
# The following line is provided for convenience purposes. It has the downside
-
# of increasing the boot-up time by auto-requiring all files in the support
-
# directory. Alternatively, in the individual `*_spec.rb` files, manually
-
# require only the support files necessary.
-
#
-
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
-
-
# Checks for pending migrations and applies them before tests are run.
-
# If you are not using ActiveRecord, you can remove these lines.
-
begin
-
1
ActiveRecord::Migration.maintain_test_schema!
-
rescue ActiveRecord::PendingMigrationError => e
-
puts e.to_s.strip
-
exit 1
-
end
-
1
RSpec.configure do |config|
-
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
-
1
config.fixture_path = "#{::Rails.root}/spec/fixtures"
-
-
# If you're not using ActiveRecord, or you'd prefer not to run each of your
-
# examples within a transaction, remove the following line or assign false
-
# instead of true.
-
1
config.use_transactional_fixtures = true
-
-
# You can uncomment this line to turn off ActiveRecord support entirely.
-
# config.use_active_record = false
-
-
# RSpec Rails can automatically mix in different behaviours to your tests
-
# based on their file location, for example enabling you to call `get` and
-
# `post` in specs under `spec/controllers`.
-
#
-
# You can disable this behaviour by removing the line below, and instead
-
# explicitly tag your specs with their type, e.g.:
-
#
-
# RSpec.describe UsersController, type: :controller do
-
# # ...
-
# end
-
#
-
# The different available types are documented in the features, such as in
-
# https://relishapp.com/rspec/rspec-rails/docs
-
1
config.infer_spec_type_from_file_location!
-
1
config.include Devise::Test::ControllerHelpers, type: :controller
-
1
config.include Devise::Test::IntegrationHelpers, type: :request
-
# Filter lines from Rails gems in backtraces.
-
1
config.filter_rails_from_backtrace!
-
# arbitrary gems may also be filtered via:
-
# config.filter_gems_from_backtrace("gem name")
-
1
config.include FactoryBot::Syntax::Methods
-
1
Shoulda::Matchers.configure do |config|
-
1
config.integrate do |with|
-
1
with.test_framework :rspec
-
1
with.library :rails
-
end
-
end
-
-
1
config.before(:each) do
-
1071
allow(Redis).to receive(:new).and_return(MockRedis.new)
-
end
-
-
1
config.before(:each) do
-
1071
ActiveJob::Base.queue_adapter = :test
-
end
-
end